티스토리 뷰
https://www.acmicpc.net/problem/2143
2143번: 두 배열의 합
첫째 줄에 T(-1,000,000,000 ≤ T ≤ 1,000,000,000)가 주어진다. 다음 줄에는 n(1 ≤ n ≤ 1,000)이 주어지고, 그 다음 줄에 n개의 정수로 A[1], …, A[n]이 주어진다. 다음 줄에는 m(1 ≤ m ≤ 1,000)이 주어지고, 그
www.acmicpc.net
이분탐색을 활용
const input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n').map(v=>v.trim())
const T = +input[0]
const a = input[2].split(' ').map(Number)
const b = input[4].split(' ').map(Number)
const X= a.reduce((r,v,i)=>{ r.push(r[i]+v); return r; },[0])
const Y= b.reduce((r,v,i)=>{ r.push(r[i]+v); return r; },[0])
let answer = 0;
let A = new Map();
for(let i = 0; i<X.length-1; i++){
for(let j = i+1; j<X.length; j++){
const subSum = X[j]-X[i]
if(!A.has(subSum)){
A.set(subSum, 1)
}else{
A.set(subSum,A.get(subSum)+1)
}
}
}
let B = [];
for(let i = 0; i<Y.length-1; i++){
for(let j = i+1; j<Y.length; j++){
const subSum = Y[j]-Y[i]
B.push(subSum)
}
}
const BB = B.sort((a,b)=>a-b)
A.forEach((v,k)=>{
const target = T-k;
let cnt = 0;
const index = find(target-1,BB);
for(let i = index; i<BB.length; i++){
if(BB[i]==target){
cnt++;
}else if(BB[i]>target){
break;
}
}
answer+=cnt*v;
})
console.log(answer)
function find(x,arr){
let min = 0;
let max = arr.length-1;
let mid;
while(min<=max){
mid = Math.floor((min+max)/2);
if(arr[mid]>x){
max = mid-1;
}else if(arr[mid]<x){
min = mid+1;
}else{
break;
}
}
return mid;
}
// console.log(find(5,[0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2]))
hant422님 풀이 참고 https://www.acmicpc.net/source/29682929
const input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n').map(v=>v.trim())
const T = +input[0]
const a = input[2].split(' ').map(Number)
const b = input[4].split(' ').map(Number)
let answer = 0;
let A = new Map();
for(let i = 0; i<a.length; i++){
let sum = 0;
for(let j = i; j<a.length; j++){
sum+=a[j]
A.set(sum,(A.get(sum) ?? 0)+1)
}
}
for(let i = 0; i<b.length; i++){
let sum = 0;
for(let j = i; j<b.length; j++){
sum+=b[j];
answer+= A.get(T-sum) ?? 0;
}
}
console.log(answer)
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js)백준 2003번: 수들의 합 2 (0) | 2022.01.08 |
---|---|
Node.js)백준 1208번: 부분수열의 합 2 (0) | 2022.01.08 |
Node.js)백준 15666번: N과 M (12) (0) | 2022.01.07 |
Node.js) 백준 15665번: N과 M (11) (0) | 2022.01.07 |
Node.js)백준 15664번: N과 M (10) (0) | 2022.01.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- MySQL
- BFS
- 서버점검
- 투포인터
- create databases;
- 로드나인
- 투포인터 연습
- create db
- 최소공통조상
- DB 생성
- MOD
- 롱베케이션
- 면접질문
- KMP
- 개발자면접
- 서버개발
- 면접비
- 은둔청년체험
- 다이나믹프로그래밍
- node.js
- 다이나밍프로그래밍
- 동적프로그래밍
- 그래프
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함