티스토리 뷰
#include <stdio.h>
#include <stdlib.h>
int n,mid,leftCnt,rightCnt,leftPoint,rightPoint;
long long ans = 0, k, tmp, arr[40];
int cmp(const void*a, const void*b) {
long long c = *(long long*)a - *(long long*)b;
if(c>0) c=1; else if(c<0) c=-1; else c=0;
return (int)c;
}
void calSub(int subCnt, int offset, long long save[]) {
int gray, prevGray = 0, diff, changeBitIndex;
long long sum = 0;
save[0] = sum;
for(int i=1;i<subCnt;i++) {
gray = i^i>>1;
diff = gray ^ prevGray;
changeBitIndex = __builtin_ctz(diff);
if(gray >> changeBitIndex & 1) sum += arr[changeBitIndex+offset];
else sum -= arr[changeBitIndex+offset];
save[i] = sum;
prevGray = gray;
}
return;
}
int main(void) {
scanf("%d %lld",&n,&k);
for(int i=0;i<n;i++)scanf("%lld",&arr[i]);
mid = (n+1)/2;
leftCnt = 1<<mid; rightCnt = 1<<(n-mid);
leftPoint = 0; rightPoint = rightCnt - 1;
long long * left = (long long*) malloc(sizeof(long long)*leftCnt);
long long * right = (long long*) malloc(sizeof(long long)*rightCnt);
calSub(leftCnt, 0, left);
calSub(rightCnt, mid, right);
qsort(left, leftCnt, 8, cmp);
qsort(right, rightCnt, 8, cmp);
while(leftPoint < leftCnt && rightPoint >=0) {
tmp = left[leftPoint] + right[rightPoint];
if(tmp > k) --rightPoint;
else {
ans += (long long)rightPoint + 1;
++leftPoint;
}
}
printf("%lld",ans);
free(left); free(right);
return 0;
}
풀이 : MITM, 비트마스크, 정렬, 두포인터
c언어 1450번 냅색문제 (백준)
#include #include int n,mid,leftCnt,rightCnt,leftPoint,rightPoint;long long ans = 0, c, tmp, arr[30];long long cmp(const void*a, const void*b) { return *(long long*)a-*(long long*)b;}void calSub(int subCnt, int offset, long long save[]) { int gray, prevGra
h202.tistory.com
와 동일합니다.
단 cmp 비교함수를 사용할 때
int cmp(const void *a, const void*b) {
return a-b;
}
이런식으로 만들면 a,b가 int 범위를 초과할 수 있기 때문에 문제가 발생하므로, 위 코드처럼 따로 정수형으로 바꿔주는 작업이 필요합니다.
'c언어 > BAEKJOON' 카테고리의 다른 글
| c언어 4160번 이혼 (백준) (0) | 2025.08.25 |
|---|---|
| c언어 1093번 스티커 수집 (백준) (0) | 2025.08.25 |
| c언어 9007번 카누 선수 (백준) (0) | 2025.08.22 |
| c언어 7453번 합이 0인 네 정수 (백준) (0) | 2025.08.21 |
| c언어 2087번 암호문 (백준) (0) | 2025.08.21 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- PASCAL
- 기하학
- C++
- find
- Krustal
- XOR
- 스택
- 백준
- 오프라인 쿼리
- Segment Tree
- C언어
- 누적 합
- BFS
- 세그먼트 트리
- 1835번
- 그리디
- union
- DFS
- 누적합
- 1835
- 최소 스패닝 트리
- 브루트포스
- 그래프
- Lazy Propagation
- 구현
- DP
- 덱
- java
- 정렬
- 문자열
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
글 보관함
