search
HomeJavajavaTutorialDetailed explanation of classic algorithmic problem of crossing the river

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 (1Output

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);
	}
}

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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.