1862 - 独木舟上的旅行
时间限制 : 3 秒
内存限制 : 128 MB
进行一次独木舟的旅行活动,独木舟可以在港口租到,并且之间没有区别。一条独木舟最多只能乘坐两个人,且乘客的总重量不能超过独木舟的最大承载量。我们要尽量减少这次活动中的花销,所以要找出可以安置所有旅客的最少的独木舟条数。现在请写一个程序,读入独木舟的最大承载量、旅客数目和每位旅客的重量。根据给出的规则,计算要安置所有旅客必须的最少的独木舟条数,并输出结果。
题目输入
第一行输入s,表示测试数据的组数;
每组数据的第一行包括两个整数w,n,80<=w<=200,1<=n<=300,w为一条独木舟的最大承载量,n为人数;
接下来的一组数据为每个人的重量(不能大于船的承载量);
题目输出
每组人数所需要的最少独木舟的条数。
输入/输出样例
输入格式
3 85 6 5 84 85 80 84 83 90 3 90 45 60 100 5 50 50 90 40 60
输出格式
5 3 3
C语言解答
#include<stdio.h> int main() { int n,w,m,i,a[300],t; scanf("%d",&n); while(n--) { scanf("%d%d",&w,&m); int k=0,j=0; for(i=0;i<m;i++) scanf("%d",&a[i]); for(i=0;i<m;i++) for(j=i+1;j<m;j++) if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } for(i=0,j=m-1;i<=j;) { if(a[i]+a[j]<=w) { i++; j--; k++; } else if(i==j) k++; else { j--; k++; } } printf("%d\n",k); } return 0; }
C++解答
#include"stdio.h" #include"algorithm" using namespace std; int main() { int s; scanf("%d",&s); while(s--) { int n,w,i,j=0; scanf("%d%d",&w,&n); int g[n]; for(i=0;i<n;i++) scanf("%d",&g[i]); sort(g,g+n); int count=0; for(i=n-1,j=0;i>=j;i--) { if(i==j) { count++; break; } else if(g[i]+g[j]<=w) { j++;count++; } else count++; } printf("%d\n",count); } return 0; }
Java解答
import java.util.Arrays; import java.util.Scanner; public class Main { static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int s=sc.nextInt(); while(s-->0) { int w=sc.nextInt(); int n=sc.nextInt(); getBoatNumbers(w,n); } } public static void getBoatNumbers(int x,int y) { int arr[]=new int[y]; for(int i=0;i<y;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); int temp=0; for(int i=0,j=arr.length-1;i<=j;) { if(arr[i]+arr[j]<=x) { temp++; i++; j--; }else if(i==j) { temp++; }else{ temp++; j--; } } System.out.println(temp); } }