同樣是在java壇做了一道作業——商品購物問題
某商店中每種商品都有一個價格
編一個程序
輸入數據
用兩個文件表示輸入數據
第一個文件INPUT.TXT的格式為:第一行是一個數字B(
第二個文件OFFER.TXT的格式為:第一行是一個數字S(
輸出數據
在輸出文件OUTPUT.TXT中寫 一個數字(占一行)
輸入/輸出數據舉例 (原例不是下面這個
INPUT
OFFER
簡析
算法
數據結構
題型
難度
編程時間
簡述
案
我做這題的時候
import java
import java
import java
import java
import java
import java
import java
public class Test
final static String STR_PRICE =
HashMap mapQuantity;
HashMap mapPrice;
Offer[] offers;
Stack stackOffer;
int minPrice;
public static void main(String[] strsArg)
Test test = new Test();
try
test
System
} catch (NumberFormatException e)
e
} catch (FileNotFoundException e)
e
} catch (IOException e)
e
}
}
public Test()
mapQuantity = new HashMap();
mapPrice = new HashMap();
stackOffer = new Stack();
}
public void init(String strInput
throws FileNotFoundException
LineNumberReader input = null;
try
input = new LineNumberReader(new InputStreamReader(
new FileInputStream(strInput)));
String str = input
int lines = Integer
int price =
for (int i =
str = input
String[] strs = str
mapQuantity
mapPrice
price += Integer
}
mapQuantity
minPrice = price;
} finally
if (input != null)
try
input
} catch (IOException e)
e
}
}
try
input = new LineNumberReader(new InputStreamReader(
new FileInputStream(strOffer)));
String str = input
int lines = Integer
offers = new Offer[lines];
for (int i =
offers[i] = new Offer();
str = input
String[] strs = str
int intOfferItems = strs
offers[i]
int old_price =
for (int j =
offers[i]
offers[i]
offers[i]
old_price += offers[i]
* ((Integer) mapPrice
}
offers[i]
offers[i]
}
} finally
if (input != null)
try
input
} catch (IOException e)
e
}
}
}
public int getMinPrice()
procMinPrice(mapQuantity);
return minPrice;
}
public void procMinPrice(HashMap mapQuantity)
boolean flg = true;
for (int i =
HashMap hashMap = getQuantityFromOffer(mapQuantity
if (hashMap == null)
continue;
flg = false;
stackOffer
procMinPrice(hashMap);
}
if (flg)
if (minPrice > ((Integer) mapQuantity
minPrice = ((Integer) mapQuantity
}
if(stackOffer
stackOffer
}
private HashMap getQuantityFromOffer(HashMap mapQuantity
if (offers[iOffer]
return null;
HashMap hashMap = new HashMap(mapQuantity);
int price = ((Integer) hashMap
for (int i =
Integer integerCount = (Integer) hashMap
if (integerCount == null)
return null;
int count = integerCount
if (count > offers[iOffer]
hashMap
else if (count == offers[iOffer]
hashMap
else
return null;
}
hashMap
+ offers[iOffer]
return hashMap;
}
class Offer
OfferItem[] offerItems;
int new_price;
int old_price;
}
class OfferItem
int id;
int count;
}
}
執行結果是
上面的程序的關鍵也就是procMinPrice函數
其他的都是周邊的讀文件和算價錢
上面程序有個嚴重問題
所以
要改進的話
上面這個改進方法是不是最好
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26607.html