今回は、実装しきる事ができませんでした・・・。こういった問題ではこんがらがる傾向にあるので(自分は)しっかり復習しないと!!
この問題は、パーティに呼べる人数の最大値を出力するプログラム作成をするものですが、すべての人が同じ話題を持っていなくてはならず、該当しない人は呼ばないというものです。改めて自分の頭の悪さを思い知らされました・・・(泣)
問題元:SRM494 Div2 Level1
public class Party {
public static int bestInvitation(String[] first, String[] second) {
int fcount = 1, scount = 1, max_count = Integer.MIN_VALUE;
for(int r = 0; r < first.length; r++) {
for(int c = r + 1; c < first.length; c++) {
if(first[r].equals(first[c]) || first[r].equals(second[c]))
fcount++;
if(second[r].equals(first[c]) || second[r].equals(second[c]))
scount++;
}
int max = Math.max(fcount, scount);
if(max > max_count) max_count = max;
}
return(max_count);
}
public static void main(String[] args) {
String[] first = new String[]{"snakes", "programming", "cobra", "monty"};
String[] second = new String[]{"python", "python", "anaconda", "python"};
System.out.println(bestInvitation(first, second));
}
}
解決案1(基本)
public static int bestInvitation(String[] first, String[] second) {
int r, c;
int ans = 0;
for(r = 0; r < first.length; r++) {
int f = 0;
int s = 0;
for(c = 0; c < first.length; c++) {
if(first[r].equals(first[c])) f++;
if(first[r].equals(second[c])) f++;
if(second[r].equals(first[c])) s++;
if(second[r].equals(second[c])) s++;
}
ans = Math.max(f, ans);
ans = Math.max(s, ans);
}
return(ans);
}
解決案2(応用)
import java.util.*;
public static int bestInvitation(String[] first, String[] second) {
HashMap<String, Integer> dic = new HashMap<String, Integer>();
for(int r = 0; r < first.length; r++) {
dic.put(first[r], 0);
dic.put(second[r], 0);
}
for(int r = 0; r < first.length; r++) {
dic.put(first[r], dic.get(first[r]) + 1);
dic.put(second[r], dic.get(second[r]) + 1);
}
int ans = 0;
for(String key : dic.keySet()) {
ans = Math.max(ans, dic.get(key));
}
return(ans);
}