Skip to content

Instantly share code, notes, and snippets.

@mia-0032
Created December 8, 2013 15:07
Show Gist options
  • Save mia-0032/7858706 to your computer and use it in GitHub Desktop.
Save mia-0032/7858706 to your computer and use it in GitHub Desktop.
https://paiza.jp/poh/ec-campaign に向けて最初書いていたJavaバージョン。 テストケース2までしかクリアできなかった。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] row = br.readLine().trim().split(" ");
//商品数
int num = Integer.parseInt(row[0]);
//キャンペーン日数
int days = Integer.parseInt(row[1]);
//商品一覧
ArrayList<Integer> items = new ArrayList<Integer>();
for(int i=0; i < num; i++){
items.add(Integer.parseInt(br.readLine().trim()));
}
//キャンペーン価格
ArrayList<Integer> campaigns = new ArrayList<Integer>();
for(int i=0; i < days; i++){
campaigns.add(Integer.parseInt(br.readLine().trim()));
}
//キャンペーン価格の最大値
Integer campaign_max = Collections.max(campaigns);
//重複した値は2個までしか必要ない
items = filterOverTripleItems(items);
//(最大価格 - 10)を超えているものは除外する
items = filterItemsByPrice(items, campaign_max - 10);
//すべての値段の組み合わせを出す
//存在する値段について値を1にする
Boolean[] pair_items = new Boolean[campaign_max + 1];
Arrays.fill(pair_items, false);
pair_items[0] = true;
int pair_price;
int first_price;
int item_num = items.size();
for(int i=0; i < (item_num - 1); i++){
first_price = items.get(i);
for(int j=i+1; j < item_num; j++){
pair_price = first_price + items.get(j);
if(pair_price > campaign_max){
continue;
}
pair_items[pair_price] = true;
}
}
//各キャンペーン価格について最大値を計算
for(int i=0; i < days; i++){
for(int p=campaigns.get(i); p >= 0; p--){
if(pair_items[p]){
System.out.println(p);
break;
}
}
}
}
private static ArrayList<Integer> filterItemsByPrice(ArrayList<Integer> items, Integer price){
ArrayList<Integer> result = new ArrayList<Integer>();
for(Integer item: items){
if(item <= price){
result.add(item);
}
}
return result;
}
private static ArrayList<Integer> filterOverTripleItems(ArrayList<Integer> items){
ArrayList<Integer> result = new ArrayList<Integer>();
Integer previous = 0;
Collections.sort(items);
int count = 1;
for(Integer item: items){
if(previous == item){
count++;
} else {
count = 1;
}
if(count < 3){
result.add(item);
}
previous = item;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment