Notice
Recent Posts
문제 풀이 및 개발 공간
[백준] 2143번 두 배열의 합 (gold 3 본문
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int t=Integer.valueOf(br.readLine());
HashMap<Integer, Integer> dict=new HashMap<>();
ArrayList<Integer> num=new ArrayList<>();
int aLen=Integer.valueOf(br.readLine());
st=new StringTokenizer(br.readLine());
for(int i=0; i<aLen; i++){
num.add(Integer.valueOf(st.nextToken()));
}
//a집합에서 만들 수 있는 모든 부분 배열 만들고, dict에 추가하기.
//dict추가시 같은 값은, 똑같은 부분배열이 증가하는 것이므로, value값 ++;
for(int i=0; i<aLen; i++){
int temp=0;
for(int j=i; j<aLen; j++){
temp+=num.get(j);
if(dict.get(temp)!=null){
dict.replace(temp, dict.get(temp)+1);
}
else{
dict.put(temp,1);
}
}
}
num.clear();
int bLen=Integer.valueOf(br.readLine());
st=new StringTokenizer(br.readLine());
for(int i=0; i<bLen; i++){
num.add(Integer.valueOf(st.nextToken()));
}
//정답을 long으로 선언한 이유는.
//만약 t가 0이고, a,b 집합의 모든 수가 0일 경우.
//a와 b는 각각 50만개의 부분배열이 발생하고.
//a+b=t가 되는 케이스는 50만*50만인 경우가 발생하기 때문이다.
//대략 2500억 정도.
long answer=0;
//b집합으로 만들 수 있는 부분집합 모두 만들면서, 이와 합이 t가 되는
//a부분배열의 갯수를 더한게 정답이 된다.
for(int i=0; i<bLen; i++){
int temp=0;
for(int j=i; j<bLen; j++){
temp+=num.get(j);
if(dict.get(t-temp)!=null){
answer+=dict.get(t-temp);
}
}
}
bw.write(answer+"");
bw.flush();
}
}
'백준공부 > java' 카테고리의 다른 글
[백준] 1082번 방 번호 (gold 3 (0) | 2024.05.08 |
---|---|
[백준] 2146번 다리 만들기 (gold 3 (0) | 2024.05.08 |
[백준] 11967번 불켜기 (gold 2 (0) | 2024.05.07 |
[백준] 19238번 스타트 택시 (gold 2 (0) | 2024.05.06 |
[백준] 16946번 벽 부수고 이동하기 4 (gold 2 (2) | 2024.05.01 |