티스토리 뷰
문제 출처: https://www.acmicpc.net/problem/2001
2001번: 보석 줍기
첫째 줄에 n, m, K가 주어진다. 다음 K개의 줄에는 보석이 있는 섬의 번호가 주어진다. 다음 m개의 줄에는 각 다리에 대한 정보를 나타내는 세 자연수 a, b, c(1 ≤ c ≤ 100)가 주어진다. 이는 a번 섬과
www.acmicpc.net
비트마스킹을 활용한 BFS이다.
visited[idx][1 << 14]를 통해 가진 보석마다 방문 배열을 다르게 사용하도록하여 문제를 해결할 수 있다.
1번 섬에서 출발하여 1번 섬으로 도착해야 하므로 일반적으로 시작점을 큐에 push해줄 때 visited도 1로 바꿔주는 방법으로 하면 1번 섬으로 돌아오는 경우를 예외로 처리해주어야 해서 그냥 큐에 push할 때 visited를 바꾸지 않았다.
또한 1번 섬에 보석이 있는 경우가 있다면 시작하자마자 보석을 줍는 경우도 함께 큐에 넣어 주었다.
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#include <string>
using namespace std;
struct T
{
int idx, jewel;
};
typedef pair<int, int>P;
int N, M, K;
int jewelIsland[15];
int visited[101][1 << 14];
int maxV = 0;
vector<P>adj[101];
int main(void)
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> N >> M >> K;
for (int i = 0; i < K; i++)cin >> jewelIsland[i];
for (int i = 0; i < M; i++) {
int a, b, c;
cin >> a >> b >> c;
adj[a].push_back(P(b, c));
adj[b].push_back(P(a, c));
}
queue<T> q;
q.push(T{ 1,0 });
for (int i = 0; i < K; i++) {
if (jewelIsland[i] == 1) {
q.push(T{ 1,1 << (i) });
}
}
while (!q.empty()) {
T curr = q.front(); q.pop();
int count = 0;
for (int i = 0; i < K; i++) {
if ((curr.jewel >> i) & 1)count++;
}
if (curr.idx == 1 && visited[curr.idx][curr.jewel] == 1) {
if (maxV < count)maxV = count;
continue;
}
for (auto next : adj[curr.idx]) {
//방문여부
if (visited[next.first][curr.jewel])continue;
//무게 초과 여부
if (next.second < count)continue;
int isFlag = 0;
int isJewel = 0;
for (int i = 0; i < K; i++) {
if (jewelIsland[i] == next.first) {
isFlag = 1;
isJewel = i;
break;
}
}
//보석섬이든 아니든 보석을 안줍는 경우
visited[next.first][curr.jewel] = 1;
q.push(T{ next.first,curr.jewel });
if (isFlag != 0) {
visited[next.first][curr.jewel | (1 << isJewel)] = 1;
q.push(T{ next.first,curr.jewel | (1 << isJewel) });
}
}
}
cout << maxV;
}
'PS' 카테고리의 다른 글
| [백준] 4386번 별자리 만들기 C++ (0) | 2022.07.11 |
|---|---|
| [백준] 1495번 기타리스트 C++ (0) | 2022.07.11 |
| [백준] 1194번 달이 차오른다, 가자. C++ (0) | 2022.07.09 |
| [백준] 1102번 발전소 C++ (0) | 2022.07.08 |
| [Codeforces] Virtual Codeforces Round #799 (Div. 4) (0) | 2022.07.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 1004
- 벨만포드
- tea time
- 6018
- 6539
- 타임머신
- 백준
- 1918
- 스택
- 7511
- 어린왕자 C++
- 후위 표기식
- C++
- 소셜네트워킹어플리케이션
- 골목길C++
- 11657
- 1738
- 상범빌딩
- 골목길
- 벨만-포드
- 중위 표기식 후위 표기식으로 변환
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
글 보관함
