https://www.acmicpc.net/problem/2637

 

2637번: 장난감조립

첫째 줄에는 자연수 N(3 ≤ N ≤ 100)이 주어지는데, 1부터 N-1까지는 기본 부품이나 중간 부품의 번호를 나타내고, N은 완제품의 번호를 나타낸다. 그리고 그 다음 줄에는 자연수 M(3 ≤ M ≤ 100)이 주

www.acmicpc.net

 

 

[난이도] Gold2
[유형] 위상정렬

[풀이]
N(완성품을) 시작점으로 해서 위상정렬을 하면서 필요한 부품의 갯수를 곱해가면 답을 구할 수 있다.

 

#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int N,M;
vector<pair<int,int>> adj[101];
int in[101],cnt[101];
int main(){
scanf("%d%d",&N,&M);
for(int i=0;i<M;i++){
int x,y,k;
scanf("%d%d%d",&x,&y,&k);
adj[x].push_back({y,k});
in[y]++;
}
vector<int> ans;
queue<int> q;
q.push(N);
cnt[N]=1;
while(!q.empty()){
int cur=q.front(); q.pop();
if(adj[cur].empty()){
ans.push_back(cur);
}
for(auto p : adj[cur]){
int nxt=p.first;
int c=p.second;
cnt[nxt]+=cnt[cur]*c;
if(--in[nxt]==0) q.push(nxt);
}
}
sort(ans.begin(),ans.end());
for(auto k : ans) printf("%d %d\n",k,cnt[k]);
}



https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Gold2/2637.cpp

+ Recent posts