uva - 10037(贪心)

先让最后两个过桥,这样总是最优的,晚过不如早过,因为借助的过桥快的人用时可能变长,

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1111;
int a[maxn],n,res=0;
int handel(int n){
  if(n == 3){
     printf("%d %d\n",a[1],a[2]);
     printf("%d\n",a[1]);
     printf("%d %d\n",a[1],a[3]);
  }
  else if(n == 2){
    printf("%d %d\n",a[1],a[2]);
  }
  else {
    printf("%d\n",a[1]);
  }
}
void solve(){
  while(n>=4){
     int x = a[n-1];
     if(2*a[1]+x <= a[1] + 2*a[2]){
        printf("%d %d\n",a[1],a[n]);
        printf("%d\n",a[1]);
        printf("%d %d\n",a[1],a[n-1]);
        printf("%d\n",a[1]);
     }
     else{
        printf("%d %d\n",a[1],a[2]);
        printf("%d\n",a[1]);
        printf("%d %d\n",a[n-1],a[n]);
        printf("%d\n",a[2]);
     }
     n-=2;
  }
  handel(n);
}
void get_num(){
  int tn = n;
  while(tn>=4){
     int x = a[tn-1];
     if(2*a[1]+x <= a[1] + 2*a[2]){
        res+=2*a[1]+x+a[tn];
     }
     else{
       res+=a[1]+2*a[2]+a[tn];
     }
     tn-=2;
  }
  if(tn==3) res+= a[1]+a[2]+a[3];
  if(tn==2) res+=a[2];
  if(tn==1) res+=a[1];
}
int main()
{
   int T;
   scanf("%d",&T);
   while(T--){
     scanf("%d",&n);
     for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
     sort(a+1,a+1+n);
     res = 0;
     get_num();
     printf("%d\n",res);
     solve();
     if(T) printf("\n");
   }
   return 0;
}


你可能感兴趣的:(uva - 10037(贪心))