티스토리 뷰

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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함