티스토리 뷰
이 문제는 "위상정렬"과 메모이제이션을 이용하여 해결할 수 있다.
인입 간선이 0인 노드를 시작점으로 하여,
건물을 지을 때 걸리는 시간을 메모하여 최종 목적하는 건물을 지을 때 걸리는 시간을 확인하면 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
/** | |
* 백준, 1005, ACM Craft | |
* | |
* @author whitebeard | |
* | |
*/ | |
public class Problem1005 { | |
static int T; // 테스트 케이스 개수 | |
static int N; // 건물의 개수 | |
static int K; // 건설 순서 규칙 | |
static int W; // 최종 생성 건물 | |
static int[] cost; // 비 | |
static int[] in; // 인입간 | |
static int[] value; // 메모 | |
@SuppressWarnings("unchecked") | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
T = sc.nextInt(); | |
while (T-- > 0) { | |
N = sc.nextInt(); | |
K = sc.nextInt(); | |
cost = new int[N + 1]; | |
in = new int[N + 1]; | |
value = new int[N + 1]; | |
for (int i = 1; i <= N; i++) | |
cost[i] = sc.nextInt(); | |
LinkedList<Integer>[] list = new LinkedList[N + 1]; | |
for (int i = 1; i <= N; i++) | |
list[i] = new LinkedList<Integer>(); // 리스트 초기화 | |
for (int i = 0; i < K; i++) { | |
int from = sc.nextInt(); | |
int to = sc.nextInt(); | |
list[from].add(to); // from -> to 간선 표현 | |
in[to]++; // 인입간선 | |
} | |
W = sc.nextInt(); | |
Queue<Integer> queue = new LinkedList<>(); | |
// 시작 정점 설정 | |
for (int i = 1; i < N + 1; i++) { | |
if (in[i] == 0) { | |
queue.add(i); | |
value[i] = cost[i]; | |
} | |
} | |
while (!queue.isEmpty()) { | |
int from = queue.poll(); | |
for (int to : list[from]) { | |
// 다음 건물의 생성 시간을 설정 | |
// from 까지 걸린 시간과 to 건물을 생성하는데 걸리는 시간의 합을 구하여 to 건물 생성에 걸린시간을 처리 | |
value[to] = Math.max(value[to], value[from] + cost[to]); | |
if (--in[to] == 0) | |
queue.add(to); | |
} | |
} | |
System.out.println(value[W]); | |
} | |
sc.close(); | |
} | |
} |
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준][DP] 5557 1학년 (0) | 2017.08.23 |
---|---|
[백준][DP] 11060 점프점프 (0) | 2017.08.23 |
[백준][트리] 1197 최소 스패닝 트리(크루스칼 알고리즘) (0) | 2017.07.06 |
[백준] 1717 집합의 표현(유니온 파인드) (0) | 2017.07.06 |
[백준][그래프] 2623 음악프로그램 (0) | 2017.07.04 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- bash
- oozie
- Python
- HIVE
- SQL
- nodejs
- 백준
- 하이브
- emr
- 하둡
- java
- airflow
- 정올
- Tez
- mysql
- 다이나믹
- Linux
- HDFS
- 오류
- S3
- ubuntu
- Hadoop
- AWS
- error
- build
- 파이썬
- SPARK
- hbase
- yarn
- 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함