您的位置:首页 > 其它

算法概论第七周作业

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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: