πŸ“¦1005: ACM_Craft


[μ•Œκ³ λ¦¬μ¦˜ 풀이] κ°•λ™κ·œ
Reviewed by Kade Kang (devkade12@gmail.com)
Reviewed:: 2024-02-20
문제 ν™•μΈν•˜κΈ°

풀이

  • μœ„μƒ μ •λ ¬ λ¬Έμ œμ΄λ‹€.
  • 건섀 μˆœμ„œκ°€ μ£Όμ–΄μ§€κΈ° λ•Œλ¬Έμ— Indegree λ₯Ό ν†΅ν•΄μ„œ μˆœμ„œλ₯Ό λ’€λ‘œ 미뀄쀀닀.
  • Res[i][j] 은 i 번째 건물을 건섀 μ™„λ£Œν•˜λŠ”λ° λ°œμƒν•˜λŠ” μ΅œμ†Œ μ‹œκ°„μ„ λ§ν•œλ‹€.
  • Res 에 μ—…λ°μ΄νŠΈ ν•  λ•ŒλŠ” λ¬Έμ œμ—μ„œ μ œμ‹œν•œ λŒ€λ‘œ λŠ¦λŠ” 건물에 μ‹œκ°„μ„ λ§žμΆ°μ•Ό ν•˜κΈ° λ•Œλ¬Έμ— μ†Œμš” μ‹œκ°„μ΄ 더 큰 건물둜 κ³„μ‚°ν•œλ‹€.
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#define endl '\n'
using namespace std;
 
int T, N, K, a, b, goal;
int Time[1001];
vector<int> Sequence[1001];
int Indegree[1001];
int Res[1001];
 
void Input(){
    cin >> N >> K;
    for(int i = 1; i <= N; i++){
        cin >> Time[i];
    }
    for(int i = 0; i < K; i++){
        cin >> a >> b;
        Sequence[a].push_back(b);
        Indegree[b]++;
    }
    cin >> goal;
}
 
void Initialize(){
    for (int i = 0; i < N; i++) Sequence[i].clear();
    memset(Time, 0, sizeof(Time));
    memset(Res, 0, sizeof(Res));
    memset(Indegree, 0, sizeof(Indegree));
}
 
void Solution(){
    queue<int> q;
    for(int i = 1; i <= N; i++){
        if(Indegree[i]==0){
            q.push(i);
            Res[i] = Time[i];
        }
    }
    while(!q.empty()){
        int cur = q.front(); q.pop();
        for(auto nxt : Sequence[cur]){
            Res[nxt] = (Res[nxt] < Res[cur]+Time[nxt]) ? Res[cur]+Time[nxt] : Res[nxt];
            Indegree[nxt]--;
            if(Indegree[nxt]==0){
                q.push(nxt);
            }
        }
    }
    cout << Res[goal] << endl;
}
 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
 
    cin >> T;
    while(T--){
        Input();
        Solution();
        Initialize();
    }
 
    return 0;
}