BOJ::14567 선수과목

[BOJ] : https://www.acmicpc.net/problem/14567

시사점

이해(4)

설계(3)

시간 복잡도

공간 복잡도

구현(15)

#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1000+1;

int n, m;
int doneWhen[MAX_N];
vector<int> adj[MAX_N];
void solve(){
    int sem = 1;
    while(true){
        bool doneOuter = true;
        for(int i = 1; i <= n; i++){
            bool doneInner = true;
            if(doneWhen[i] != 0) continue;
            if(adj[i].size() == 0){
                doneOuter = false;
                doneWhen[i] = sem;
                continue;
            }

            for(int j = 0; j < adj[i].size(); j++){
                int pre = adj[i][j];
                if(doneWhen[pre] == 0 || doneWhen[pre] == sem){
                    doneOuter = false;
                    doneInner = false;
                    break;
                }
            }
            if(doneInner == true){
                doneOuter = false;
                doneWhen[i] = sem;
            }
        }
        if(doneOuter == true)
            break;
        sem++;
    }
    for(int i = 1 ; i <= n; i++){
        if(i != n) cout << doneWhen[i] <<" ";
        else cout << doneWhen[i]<<endl;
    }
}
int main(){
    freopen("input.txt", "r", stdin);
    cin >> n >>  m;
    for(int i = 0; i < m; i++){
        int x, y;
        cin >> x >> y;
        adj[y].push_back(x);
    }
    solve();
    return 0;
}

디버깅(x)

좋은 코드

for(int x : adj[i])
    ret = max(ret, f(x));
return ++ret;
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int dp[1001];
vector<int> adj[1001];

int f(int i)
{
	int &ret = dp[i];
	if (ret)
		return ret;
	for (int x : adj[i])
		ret = max(ret, f(x));
	return ++ret;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	int n, m, i;
	cin >> n >> m;
	while (m--)
	{
		int a, b;
		cin >> a >> b;
		adj[b].push_back(a);
	}

	for (i = 1; i <= n; i++)
		cout << f(i) << ' ';
}

최적화