1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 成本与利润最大化

成本与利润最大化

时间:2019-12-03 06:20:38

相关推荐

成本与利润最大化

问题描述:

编程实现并输出当所获得的利润最大时,资源的投入方案。

样例如下:

结果如下:

代码如下:

import java.util.Arrays;import java.util.Scanner;public class MaxProfit {public static int[] findsite(double target,double [][] newmatch)//寻找位置{int []res=new int[2];for (int i = 0; i <newmatch.length ; i++) {for (int j = 0; j <newmatch[0].length ; j++) {if (Math.abs(newmatch[i][j]-target)< 0.000001){res[0]=i;res[1]=j;}}}return res;}public static int[] maxprofit(int projectcount,int resourcecount,int [][]match){int []res=new int[projectcount];//用于结果返回Arrays.fill(res,-1);//结果数组用-1填充double [][]newmatch=new double[projectcount][resourcecount];for (int i = 0; i <match.length ; i++) {for (int j = 0; j <match[0].length ; j++) {newmatch[i][j]=match[i][j]/((j+1)*1.0);}}double []temp=new double[projectcount*resourcecount];for (int i = 0; i <temp.length ; i++) {temp[i]=newmatch[i/resourcecount][i%resourcecount];}Arrays.sort(temp);for (int i = temp.length-1; i >0 ; i--) {int []tempsite=findsite(temp[i],newmatch);//找到最大值的位置int projectid=tempsite[0];//项目编号int resourceid=tempsite[1]+1;//资源数量if (res[projectid]==-1&&resourcecount>=resourceid) {//没有被填充resourcecount=resourcecount-resourceid;res[projectid] = resourceid-1;}}return res;}//贪心算法public static void main(String[] args) {Scanner scanner=new Scanner(System.in);System.out.print("请输入工程项目总数n:");int projectcount=scanner.nextInt();//工程总数System.out.print("请输入资源份额总数m:");int resourcecount=scanner.nextInt();//资源总数int [][]match=new int[projectcount][resourcecount];System.out.println("请输入工程项目与投入资源份额数所对应利润:");for (int i = 0; i <projectcount ; i++) {for (int j = 0; j <resourcecount ; j++) {match[i][j]=scanner.nextInt();}}int []res=maxprofit(projectcount,resourcecount,match);int maxvalue=0;for (int i = 0; i <res.length ; i++) {if (res[i]==-1){res[i]=0;continue;}maxvalue+=match[i][res[i]];res[i]=res[i]+1;}for (int i = 0; i <projectcount ; i++) {System.out.println("给工程"+(i+1)+"投入"+res[i]+"个份额,");}System.out.println("可达到最大利润:"+maxvalue);}}

运行结果如下:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。