Home Java javaTutorial Detailed explanation of classic algorithmic problem of crossing the river

Detailed explanation of classic algorithmic problem of crossing the river

Apr 30, 2019 pm 03:26 PM
java algorithm

The main content of this article is a detailed explanation of the classic algorithm problem of crossing the river. Interested friends can learn more I hope it helps you.

Description

A group of N people want to cross the river in a boat. This boat can only carry two people at most. So some kind of shuttle arrangement has to be put in place to paddle back and forth so that everyone can get across. Everyone has a different rowing speed; the speed of a pair of runners depends on the speed of the slower person. Your job is to determine a strategy that will minimize the time it takes these people to cross the river.
Input

The first line of input contains an integer T (1<=T<=20), the number of test cases. Next are T cases. The first line of each case contains N, and the second line contains N integers giving the time for each person to cross the river. Each case is preceded by a blank line. There won't be more than 1,000 people, and no one will need more than 100 seconds to cross.
Output

For each test case, print a line containing the total number of seconds it took for all N people to cross the river.
Sample input

1
4
1 2 5 10
Sample output

17

-------------------------------------------------- -------------------------------------------------- --------------------------------

problem analysis
(The speeds of the following N people are represented by abcd..., and are sorted in ascending order of speed)

  1. When n= 1, time is a
  2. When n= 2, time Then it is b
  3. When n= 3, time is a b c (a crosses the river with any person, a comes back, and then crosses the river with the remaining people)
  4. When n>= 4, the problem is much more complicated, because if any two people cross the river, there are many situations where one of them comes back after crossing the river. We need to analyze it here
    Observing the question, we can find that there are two most important points in crossing the river.
    Scheme [1] For two people crossing the river, the time spent is determined by the longest person
    In view of this, we can put the slowest d and the second slowest c together, so that the second slowest time c Just ignored.
    Plan [2] The time spent by a person who comes back is determined by him alone
    In view of this, we can let the fastest a send the others one by one, and then let the fastest a take the boat Send it back

    Realize the above solution
    When n = 4 (The speed of N people below is represented by abcd..., and according to the speed Sorting in ascending order) () indicates the time spent
    Scheme [1] abcd
    ab (b) past
    a (a) back
    cd (d) past
    b (b) back
    ab(b) past
    Time spent: a 3b d

    Plan [2] abcd
    ad(d) past
    a(a) back
    ac (c) past
    a (a) back
    ab (b) past
    Time spent : 2a b c d

    Calculation example
    Now we import the question sample {1, 2, 5, 10}
    Plan [1] Time = 17
    Plan [2] Time = 19
    So use plan [1] It takes the shortest time, the time is 17

    But if we modify the data {1, 2, 2, 10}
    Scheme [1] time = 17
    Scheme [2] time = 16
    This time, plan [2] takes the shortest time, with a time of 16;

    If we approximate the time spent by the two plans,
    Plan [1]: 2b
    plan [2]: a c
    It can be seen that the time spentThe decisive factor lies in the fastest a, the second fastest b and the second slowest c. We only need to compare 2b and a c and choose to spend The solution that takes the least time is sufficient.

    When n > 4We can express it as using the first two fastest people to transport the slowest two people, and the number of people will be reduced by 2 after transporting.

    Related tutorials: Java video tutorial

    The following is the AC code, for reference only

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class 过河         
    {
    	static long time = 0L;
    	public static void main(String[] args)
    	{
    		Scanner sc = new Scanner(System.in);
    		int m = sc.nextInt();
    		for (int i = 0; i < m; i++)
    		{
    			int n = sc.nextInt();
    			int[] A = new int[n];
    			for (int j = 0; j < n; j++)
    			{
    				A[j] = sc.nextInt();
    			}
    			Arrays.sort(A);
    			f(A);
    			System.out.println(time);
    			time = 0L;
    		}
    	}
    	public static void f(int[] A) {
    		if(A.length == 3) {
    			time += A[0] + A[1] + A[2];
    			return;
    		}
    		if(A.length == 2) {
    			time += A[1];
    			return;
    		}
    		if(A.length == 1) {
    			time += A[0];
    			return;
    		}
    		if(A[0] + A[A.length - 2] < A[1] * 2) {
    			time += 2 * A[0] + A[A.length - 2] + A[A.length - 1];
    		}else {
    			time += A[0] + 2 * A[1] + A[A.length - 1];
    		}
    		int[] B = Arrays.copyOfRange(A, 0, A.length - 2);
    		f(B);
    	}
    }
    Copy after login

    The above is the detailed content of Detailed explanation of classic algorithmic problem of crossing the river. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles