Home [백준 2143번] 두 배열의 합 [C언어]
Post
Cancel

[백준 2143번] 두 배열의 합 [C언어]

2143번: 두 배열의 합

문제 링크: 2143번: 두 배열의 합


전체 코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h> 
#include <stdlib.h>
#pragma warning(disable:4996)
#pragma warning(disable:6031)

#define MAX_LEN 1000

int cmp(const void *a, const void *b);
void inputArr(int *arr, int len);
void makePrtlSum(int *orgnArr, int *newArr, int len, int *pIdx);

int main() {

	int s, len1, len2, arr1[MAX_LEN + 1] = { 0 }, arr2[MAX_LEN + 1] = { 0 };
	int prtlSum1[MAX_LEN * MAX_LEN], prtlSum2[MAX_LEN * MAX_LEN], sumIdx1 = 0, sumIdx2 = 0;
	long long cnt = 0;
	scanf("%d %d", &s, &len1);
	inputArr(arr1, len1);
	scanf("%d", &len2);
	inputArr(arr2, len2);

	makePrtlSum(arr1, prtlSum1, len1, &sumIdx1);
	makePrtlSum(arr2, prtlSum2, len2, &sumIdx2);

	qsort(prtlSum1, sumIdx1, sizeof(int), cmp);
	qsort(prtlSum2, sumIdx2, sizeof(int), cmp);

	int i0 = 0, j0 = sumIdx2 - 1;
	while (i0 < sumIdx1 && j0 >= 0) {
		if (prtlSum1[i0] + prtlSum2[j0] == s) {
			long long currCnt = 0;
			int i, j;
			for (i = i0; prtlSum1[i0] == prtlSum1[i] && i < sumIdx1; i++);
			for (j = j0; prtlSum2[j0] == prtlSum2[j] && j >= 0; j--);
			cnt += (long long)(i - i0) * (j0 - j);
			i0 = i, j0 = j;
		}
		else if (prtlSum1[i0] + prtlSum2[j0] < s) i0++;
		else j0--;
	}

	printf("%lld", cnt);

	return 0;
}


void inputArr(int *arr, int len) {
	for (int i = 1; i <= len; i++) {
		scanf("%d", &arr[i]);
		arr[i] += arr[i - 1];
	}
	return;
}

void makePrtlSum(int *orgnArr, int *newArr, int len, int *pIdx) {
	for (int i = 1; i <= len; i++) {
		for (int j = 0; j < i; j++) {
			newArr[(*pIdx)++] = orgnArr[i] - orgnArr[j];
		}
	}
	return;
}

int cmp(const void *a, const void *b) {
	if (*(int *)a > *(int *)b) return 1;
	if (*(int *)a < *(int *)b) return -1;
	return 0;
}

This post is licensed under CC BY 4.0 by the author.

[CS] 여러가지 정렬 알고리즘

[백준 17822번] 원판 돌리기 [C언어]