UVA10037 Bridge ---- 贪心

题意:

N个人夜里过河,总共只有一盏灯,每次最多过两个人,然后需要有人将灯送回

才能继续过人,每个人过桥都需要耗费一定的时间(最大),让你求耗费的最少时间,并输出过河方案

题解: 将花费时间从小到大排序后, a0,a1,ai,ai+1这4个人,有2种方案

①让最快的人把最慢的两个人送过去

②最快的2个人先快去,最快的再回来,这样将a1留在对面,然后ai和ai+1过去,然后让a1再回来

这样每轮送过去2个人,每轮取2种方案中最节约时间的即可

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
int time[2000];
struct Node {
  int a,b;
  void Print() {
    if(b == -1) {
      printf("%d\n",a);
    } else {
      printf("%d %d\n",a,b);
    }
  }
} node[2000];

int main() {
  int T;
  scanf("%d",&T);
  while(T--) {
    scanf("%d",&n);
    for(int i = 0;i < n;i++) scanf("%d",&time[i]);
    sort(time,time+n);
    int res = 0;
    int cnt = 0;
    while(n >= 4) {
      int a,b;
      a = time[n-1]+time[n-2]+time[0]*2;
      b = time[1]*2+time[n-1]+time[0];
      if(a <= b) {
        res += a;
        node[cnt++] = (Node){time[0],time[n-1]};
        node[cnt++] = (Node){time[0],-1};
        node[cnt++] = (Node){time[0],time[n-2]};
        node[cnt++] = (Node){time[0],-1};
      } else {
        res += b;
        node[cnt++] = (Node){time[0],time[1]};
        node[cnt++] = (Node){time[0],-1};
        node[cnt++] = (Node){time[n-2],time[n-1]};
        node[cnt++] = (Node){time[1],-1};
      }
      n -= 2;
    }
    if(n == 3) {
      res += time[2]+time[0]+time[1];
      node[cnt++] = (Node){time[0],time[2]};
      node[cnt++] = (Node){time[0],-1};
      node[cnt++] = (Node){time[0],time[1]};
      n -= 3;
    }
    if(n == 2) {
      res += time[1];
      node[cnt++] = (Node){time[0],time[1]};
      n -= 2;
    }
    if(n == 1) {
      res += time[0];
      node[cnt++] = (Node){time[0],-1};
      n -= 1;
    }
    printf("%d\n",res);
    for(int i = 0;i < cnt;i++) node[i].Print();
    if(T) printf("\n");
  }

  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值