钢条切割问题(Java)——暴力法(Brute force)

Rod Cutting题目:

在这里插入图片描述

  • 注意:
  1. 本题采用txt文件读入,屏幕输出;
    如果需要屏幕读入屏幕输出,可以留言或者自己改代码~
  2. 说明:暴力法(Brute force): 列出每种切割方案,比较哪种切割方案利润最大,——所需时间T=O(2^n )
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Bruteforce {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		long startTime = System.currentTimeMillis();
		try {
		FileReader in = new FileReader("p2.txt");
		BufferedReader inin=new BufferedReader(in);//读入文件
		 	try {
		 		String s="";
		 		int i=0;		 		
				int[] Length=new int[100];//Rod的长度
				int[] Price=new int[100];//Rod的价值
		 		while((s=inin.readLine())!=null)
		 		{  
			 		//System.out.println(s);
			 	    //将每一行分为两个整数
			 		String []data=s.split(" ");
			 		//System.out.println("长度"+data.length);
			 		int [] datas=new int[data.length];//存入每一行String类型的数组data[0]  data[1]  
			 		//将String类型数组转成int类型
			 		for(int j=0;j<data.length;j++)
			 		{   datas[j]=Integer.parseInt(data[j]); } //将String类型转换成int类型
	//		 		for(int i=0;i<datas.length;i++)
	//		 		{    System.out.println(i+" "+datas[i]+" ");   } 	
			 		Length[i]=datas[0]; //获取Rod的长度
			 		Price[i]=datas[1];  //获取Rod的价值
			 		//System.out.println(data);
			 			i++;
		 		}
//		 		for(int k=0;k<i;k++)
//		 		{    System.out.println(k+" "+Length[k]+" ");   } //Rod的长度Length
//		 		for(int k=0;k<i;k++)
//		 		{    System.out.println(k+" "+Price[k]+" ");   } //Rod的价格Price
		 		Scanner scanner=new Scanner(System.in);
		 		System.out.print("请输入Rod的长度: ");
		 		int n=scanner.nextInt();//Rod的长度
		 		System.out.println("Maximum revenue: "+Cut_Rod(Price,n));//输出最大利润
		 		
		 	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
	    System.out.print("方法:暴力法(Brute force); 执行时间: "+(endTime-startTime)+" ms");//求得程式执行时间
	}
	static int Cut_Rod(int price[],int n)//Bruteforce暴力法: 求解最大利润
	{
		if(n==0)
			{  return 0;}//无法切割: return 0
		else{
			int  q=Integer.MIN_VALUE;//q无穷小
			for(int i=1;i<=n;i++)
			{
				q=Math.max(q, price[i-1] + Cut_Rod(price, n - i));//取q和已分割求得的价值中取max
			}
			//System.out.println(q+" ");
			return q;
		}		
	}
}

运行成功,截图如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Laura_Wangzx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值