算法概论第七周作业
2014-04-25 22:49
267 查看
import java.io.*; public class Knapsack { static int max(int a,int b) { if(a>b) return a; else return b; } public static void main(String[] args) { try { FileReader fr=new FileReader("d:\\1\\Knapsack.txt"); BufferedReader br=new BufferedReader(fr); int w,i,t1,a,b; String str=""; while((t1=br.read())!=' ') { str = str + (char) t1; } w = Integer.parseInt(str.trim()); str=""; while((t1=br.read())!='\n') { str = str + (char) t1; } i = Integer.parseInt(str.trim()); str=""; //System.out.println(w); //System.out.println(i); int[][] wv=new int[i][2]; int ki=i+1,kw=w+1; i++;w++; int[][] k=new int [i][w]; a=0; int t2; while((t2=br.read())!=-1) { str = str + (char) t2; if((char)t2==' ') { wv[a][0] = Integer.parseInt(str.trim()); str=""; //System.out.println(wv[i][0]); } if((char)t2=='\n') { wv[a][1] = Integer.parseInt(str.trim()); str=""; a++; } } //单副本方法 for(a=0;a<i;a++) k[a][0]=0; for(a=0;a<w;a++) k[0][a]=0; for(a=1;a<i;a++) for(b=1;b<w;b++) { if(wv[a-1][0]>b) k[a][b]=k[a-1][b]; else k[a][b]=max(k[a-1][b],k[a-1][b-wv[a-1][0]]+wv[a-1][1]); //由于在上面i和w都已经增加了1,所以这里a-1才能取到原来的i的最大值 } //System.out.println(k[a][b]); FileOutputStream fos = new FileOutputStream("d:\\1\\KnapsackResult01.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "gb2312"); BufferedWriter bw = new BufferedWriter(osw); str=""; for(a=0;a<i;a++) { for(b=0;b<w;b++) { str=str+Integer.toString(k[a][b])+" "; System.out.print(k[a][b]+" "); } bw.write(str); bw.newLine(); str=""; System.out.println(); } bw.close(); osw.close(); //多副本背包方法 int[] k1=new int[w]; k1[0]=0; t1=0; for(a=1;a<w;a++) { for(b=0;b<i-1;b++) { if(wv[b][0]<=a) { if(t1<k1[a-wv[b][0]]+wv[b][1]) { t1=k1[a-wv[b][0]]+wv[b][1]; } //System.out.println(t1); } } k1[a]=t1; } //System.out.println(a); //System.out.println(k1[a-1]); System.out.println(); FileOutputStream fos1 = new FileOutputStream("d:\\1\\KnapsackResult02.txt"); OutputStreamWriter osw1 = new OutputStreamWriter(fos1, "gb2312"); BufferedWriter bw1 = new BufferedWriter(osw1); str=""; for(a=0;a<w;a++) { System.out.print(k1[a]+" "); str=str+Integer.toString(k1[a])+" "; } bw1.write(str); bw1.newLine(); bw1.close(); osw1.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
相关文章推荐
- 嵌入式文件系统:NTFS和EXFAT比较
- 嵌入式文件系统:NTFS和EXFAT比较
- 合并两个排序的链表(递归算法)
- 安卓Json数据的解析
- linux目录
- SUSE Linux 报错:too many open files in system
- Spring集成Restlet实践
- OpenCV 直方图计算函数 calcHist源码深度剖析
- C++迭代器失效讨论
- SVN服务器搭建和使用(四)
- 数据结构《16》----自动补齐实现《一》----Trie 树
- 位块传输 BitBlt与StretchBlt
- MVC4 js里给对象赋值
- 数据结构《16》----自动补齐实现《一》----Trie 树
- SVN服务器搭建和使用(三)
- SVN服务器搭建和使用(二)
- Java中的数组和字符串
- hdu 4496 D-City(并查集)
- 词法分析
- 最小费用最大流模板