๐๐ปโโ๏ธ ์ฐ์ ์์ ํ ์ฌ์ฉ!
๊ณจ๋4๋ผ์ ์กฐ๊ธ ์ด๋ ต๊ฒ ๋ค ์๊ฐํ๋๋ฐ, ์๋๋ค.
์๊ฐํด๋ณด๋ฉด, ํ์ผ์ ๋ฌด์กฐ๊ฑด 2๊ฐ์ฉ ํฉ์ณ์ง๊ธฐ๋๋ฌธ์ ์ด๋ป๊ฒ ํฉ์น๋ ํ์๋ ๊ณ ์ ์ด๋ค!
๋์ผํ ํ์์ ์ต์๋น์ฉ์ ๊ตฌํ๋ ค๋ฉด, ๊ฐ ํ์๋ง๋ค ํฉ์ด ์ต์๊ฐ ๋๋๋กํ๋ฉด๋๋ค.
๋ฐ๋ผ์ ์ฐ์ ์์ ํ๋ฅผ ์ด์ฉํ๋ค!
import java.util.*;
import java.io.*;
public class Main {
static PriorityQueue<Integer> pq = new PriorityQueue<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int i=0; i<T; i++) {
int answer = 0;
pq.clear();
int K = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=0; j<K; j++) {
pq.add(Integer.parseInt(st.nextToken()));
}
while(!pq.isEmpty()) {
if(pq.size() == 1) {
break;
}
int sum = pq.poll() + pq.poll();
answer += sum;
pq.add(sum);
}
System.out.println(answer);
}
}
}
ํ ์ผ๋ ํต๊ณผํ๋๋ฐ, ํ๋ ธ์ต๋๋ค๋ฅผ ๋ฐ์๋ค.
ํ์ ์ด int์ธ๊ฒ ๋ฌธ์ ์๋ค! ๋ฒ์๋ฅผ ์ด๊ณผํ๋ค.
int๊ด๋ จ๋ถ๋ถ long์ผ๋ก ์์
import java.util.*;
import java.io.*;
public class Main {
static PriorityQueue<Long> pq = new PriorityQueue<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int i=0; i<T; i++) {
long answer = 0;
pq.clear();
int K = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=0; j<K; j++) {
pq.add(Long.parseLong(st.nextToken()));
}
while(!pq.isEmpty()) {
if(pq.size() == 1) {
break;
}
long sum = pq.poll() + pq.poll();
answer += sum;
pq.add(sum);
}
System.out.println(answer);
}
}
}