第一题是0-1背包问题, 用贪心算法解, 通过14%
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.Scanner;
publicclassMain4{
publicstaticvoidmain(String[]args){
Scannersc=newScanner(System.in);
intlength=Integer.parseInt(sc.nextLine());
String[]widthsStr=sc.nextLine().split(",");
String[]valuesStr=sc.nextLine().split(",");
sc.close();
intn=widthsStr.length;
Commodity[]commodities=newCommodity[n];
for(inti=0;i
Commoditycommodity=newCommodity(Integer.parseInt(widthsStr[i]),Integer.parseInt(valuesStr[i]));
commodities[i]=commodity;
}
//按单位价值从大到小排序
Arrays.sort(commodities,Collections.reverseOrder());
intans=solve(commodities,n,length);
System.out.println(ans);
}
privatestaticintsolve(Commodity[]commodities,intn,intlength){
inttmpLength=length;
intmaxValue=0;
for(inti=0;i
if(tmpLength-commodities[i].getWidth()
continue;
tmpLength-=commodities[i].getWidth();
maxValue+=commodities[i].getValue();
}
returnmaxValue;
}
}
classCommodityimplementsComparable{
privatedoublewidth;
privatedoublevalue;
privatedoubleunitValue;
publicCommodity(doublewidth,doublevalue){
this.width=width;
this.value=value;
this.unitValue=(width==0)0:value/width;
}
publicdoublegetWidth(){
returnwidth;
}
publicvoidsetWidth(doublewidth){
this.width=width;
}
publicdoublegetValue(){
returnvalue;
}
publicvoidsetValue(doublevalue){
this.value=value;
}
publicdoublegetUnitValue(){
returnunitValue;
}
publicvoidsetUnitValue(doubleunitValue){
this.unitValue=unitValue;
}
@Override
publicintcompareTo(Commoditycommodity){
doublevalue=commodity.unitValue;
if(unitValue>value)
return1;
if(unitValue
return-1;
return0;
}
} 第二题是给一个图像, 问给定的字符串能否在图像中连续
importjava.util.Scanner;
publicclassMain2{
staticchar[][]photo={
{‘0’,‘1’,‘C’,‘H’,‘A’},
{‘9’,‘E’,‘7’,‘B’,‘I’},
{‘K’,‘D’,‘4’,‘8’,‘J’},
{‘6’,‘5’,‘F’,‘G’,‘O’},
{‘L’,‘N’,‘M’,‘2’,‘3’}};
staticintdx[]={-1,0,1,0};
staticintdy[]={0,1,0,-1};
publicstaticvoidmain(String[]args){
Scannersc=newScanner(System.in);
booleanflag;
Stringstr;
while(sc.hasNext()){
str=sc.nextLine();
flag=isLianxu(str);
if(flag==false){
System.out.println(“N”);
}else{
System.out.println(“Y”);
}
}
sc.close();
}
privatestaticbooleanisLianxu(Stringstr){
charc=str.charAt(0);
for(inti=0;i
for(intj=0;j
if(c==photo[i][j]){
returndfs(str,1,i,j);
}
}
}
returnfalse;
}
privatestaticbooleandfs(Stringstr,intindex,inti,intj){
if(str.length()==index){
returntrue;
}
for(intd=0;d
intx=i+dx[d],y=j+dy[d];
if(isSafe(x,y)&&str.charAt(index)==photo[x][y]){
returndfs(str,index+1,x,y);
}
}
returnfalse;
}
privatestaticbooleanisSafe(inti,intj){
if(i>=0&&i<=4&&j>=0&&j<=4){
returntrue;
}
returnfalse;
}
} 第三题, 字符串解码
importjava.util.Scanner;
publicclassMain1{
publicstaticvoidmain(String[]args){
Scannersc=newScanner(System.in);
Stringstr=sc.nextLine();
sc.close();
Stringans=method(str);
System.out.println(ans);
}
privatestaticStringmethod(Stringstr){
StringBuffersb=newStringBuffer();
for(inti=0,j=1;j
intcount=str.charAt(i)-‘0’;
charvalue=str.charAt(j);
for(intk=0;k
sb.append(value);
}
}
returnsb.toString();
}
}