zoukankan      html  css  js  c++  java
  • poj1700

    A group of N people wishes to go across a river with only one boat, which can at most carry two persons. Therefore some sort of shuttle arrangement must be arranged in order to row the boat back and forth so that all people may cross. Each person has a different rowing speed; the speed of a couple is determined by the speed of the slower one. Your job is to determine a strategy that minimizes the time for these people to get across.
     

     

    Input
    The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. The first line of each case contains N, and the second line contains N integers giving the time for each people to cross the river. Each case is preceded by a blank line. There won't be more than 1000 people and nobody takes more than 100 seconds to cross.
     

     

    Output
    For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
     

     

    Sample Input
    1
    4
    1 2 5 10
     

     

    Sample Output
    17
     

    题意是N个人过河,船每次只能坐两个人,船载每个人过河的所需时间不同,问最快的过河时间。

     解题思路:当n=1,2,3时所需要的最小时间很容易求得,现在由n>=4,假设n个人单独过河所需要的时间存储在数组t中,将数组t按升序排序,那么 这时将单独过河所需要时间最多的两个旅行者送到对岸去,有两种方式:
          1> 最快的(即所用时间a[0])和次快的过河,然后最快的将船划回来,再次慢的和最慢的过河,然后次快的将船划回来.

              即所需时间为:a[0]+2*a[1]+a[n-1]
          2> 最快的和最慢的过河,然后最快的将船划回来,再最快的和次慢的过河,然后最快的将船划回来.

              即所需时间为:2*a[0]+a[n-2]+a[n-1]

              这样就将过河所需时间最大的两个人送过了河,而对于剩下的人,采用同样的处理方式,接下来做的就是判断怎样用的时间最少.

     

     

    代码::

    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    using namespace std;
    int main()
    {
        int t,n,a[1001],i,sum;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d",&n);
            sum=0;
            for(i=0; i<n; i++)
                scanf("%d",&a[i]);
            sort(a,a+n);
            for(i=n-1; i>2; i-=2)
                if(a[0]+2*a[1]+a[i]>2*a[0]+a[i-1]+a[i])
                    sum+=2*a[0]+a[i-1]+a[i];
                else
                    sum+=a[0]+2*a[1]+a[i];
            if(i==2)
                sum+=a[0]+a[1]+a[2];
            else if(i==1)
                sum+=a[1];
            else
                sum+=a[0];
            printf("%d ",sum);
        }
        return 0;
    }

  • 相关阅读:
    第二章Redis管理实战
    第一章Redis入门部署及持久化介绍
    数据库命令
    第一章MySQL介绍及安装
    第十一章 MHA高可用及读写分离
    第八章 日志管理
    第九章 备份和恢复
    第十章 主从复制
    关系型数据库和非关系型数据库的对比
    MySQL面试题
  • 原文地址:https://www.cnblogs.com/lxm940130740/p/3442111.html
Copyright © 2011-2022 走看看