首页 > 搜索 > BFS搜索 > POJ 2573 Bridge [解题报告] Java
2013
11-11

POJ 2573 Bridge [解题报告] Java

Bridge

问题描述 :

n people wish to cross a bridge at night. A group of at most two people may cross at any time, and each group must have a flashlight. Only one flashlight is available among the n people, so some sort of shuttle arrangement must be arranged in order to return the flashlight so that more people may cross.

Each person has a different crossing speed; the speed of a group is determined by the speed of the slower member. Your job is to determine a strategy that gets all n people across the bridge in the minimum time.

输入:

The first line of input contains n, followed by n lines giving the crossing times for each of the people. There are not more than 1000 people and nobody takes more than 100 seconds to cross the bridge.

输出:

The first line of output must contain the total number of seconds required for all n people to cross the bridge. The following lines give a strategy for achieving this time. Each line contains either one or two integers, indicating which person or people form the next group to cross. (Each person is indicated by the crossing time specified in the input. Although many people may have the same crossing time the ambiguity is of no consequence.) Note that the crossings alternate directions, as it is necessary to return the flashlight so that more may cross. If more than one strategy yields the minimal time, any one will do.

样例输入:

4
1
2
5
10

样例输出:

17
1 2
1
5 10
2
1 2

解题代码:

//* @author: [email protected]
import java.util.*;
public class Main
{
 public static void main(String[] args)
 {
  Scanner in=new Scanner(System.in);
  int a=in.nextInt();
  ArrayList< Integer> t=new ArrayList< Integer>();
  for(int i=0;i< a;i++)
	t.add(in.nextInt());
  if(a==1){
	System.out.println(t.get(0));
	System.out.println(t.get(0));
  }
  else{
    int total=0;
    Collections.sort(t);
    ArrayList< Integer> t2=new ArrayList< Integer>();
    ArrayList< Integer> t3=new ArrayList< Integer>();
    int m1=t.get(0);
    int m2=t.get(1);
    int w=a;
    while(w>3)
    {
	total+=t.get(w-1)+m1+Math.min(m2*2,m1+t.get(w-2));
	if(m2*2>(m1+t.get(w-2)))
	{
		t2.add(m1);
		t2.add(t.get(w-2));
		t3.add(m1);
		t2.add(m1);
		t2.add(t.get(w-1));
		t3.add(m1);
	}
	else
	{
		t2.add(m1);
		t2.add(m2);
		t3.add(m1);
		t2.add(t.get(w-2));
		t2.add(t.get(w-1));
		t3.add(m2);
	}
	w-=2;
     }
    if(w==2){
	total+=m2;
	t2.add(m1);
	t2.add(m2);
     }
    else {
	total+=m1+m2+t.get(2);
	t2.add(m1);
	t2.add(m2);
	t3.add(m1);
	t2.add(m1);
	t2.add(t.get(2));

     }
     System.out.println(total);
     for(int i=0;i< a-2;i++)
     {
	System.out.println(t2.get(i*2)+" "+t2.get(i*2+1));
	System.out.println(t3.get(i));
     }
     System.out.println(t2.get(a*2-4)+" "+t2.get(a*2-3));
   }
 }
}