SWEA_D4_5643
π [D4_5643] ν€ μμ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static int N;
static int[][] adjMatrix;
public static void main(String[] args) throws IOException {
StringTokenizer st;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
sb.append("#").append(tc).append(" ");
// νμμ
N = Integer.parseInt(br.readLine());
// λΉκ΅ νμ
int M = Integer.parseInt(br.readLine());
// νμλ²νΈ 1λΆν° μμνλλ‘..
// μΈμ νλ ¬ : 0μ΄λ©΄ ν€κ΄κ³ λͺ¨λ¦ 1μ΄λ©΄ μμ λ³΄λ€ ν€κ° ν° νμκ³Όμ κ΄κ³λ₯Ό νν
adjMatrix = new int[N + 1][N + 1];
// νμμ μΈ κ²μΌλ‘ μ΄κΈ°ν ( λλ³΄λ€ ν¬κ±°λ μμμ λ€μ΄ μλ κ²½μ° 0μ΄ λμ¬ μ μκΈ° λλ¬Έμ ꡬλΆνκΈ° μν΄ -1λ‘ μ΄κΈ°ν ν΄μ€λ€.)
for (int i = 1; i <= N; i++) {
adjMatrix[i][0] = -1;
}
// λ€λκ³ λλ©΄ λ°°μ΄μ΄ μμ±
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
// aλ³΄λ€ bκ° ν¬λ€
adjMatrix[a][b] = 1;
}
for (int i = 1; i <= N; i++) {
// νμμ μΈ νμλ€λ§ νμ
if (adjMatrix[i][0] == -1) {
gtDfs(i);
}
}
// λλ³΄λ€ μμ νμμ μΉ΄μ΄ν
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
adjMatrix[0][j] += adjMatrix[i][j];
}
}
// μμ μ ν€λ₯Ό μ μ μλ νμ μ
int answer = 0;
// μ΄ ν© κ΅¬νκΈ°
for (int i = 1; i <= N; i++) {
if(adjMatrix[i][0] + adjMatrix[0][i] == N-1) {
answer++;
}
}
sb.append(answer).append("\n");
}
System.out.println(sb);
}
// μμ λ³΄λ€ ν° νμ νμ
static void gtDfs(int cur) {
for (int i = 1; i <= N; i++) {
// μ리
// i > j && j > z -> i > z
// λλ³΄λ€ ν° νμμ΄λ©΄
if (adjMatrix[cur][i] != 0) {
// νμν μ μλ€
if (adjMatrix[i][0] == -1) {
gtDfs(i);
}
// λλ³΄λ€ ν° νμμ΄ μκ³ μλ λ€λ₯Έ νμκ³Όμ ν€ κ΄κ³λ₯Ό λμμ μ§μ κ΄κ³λ‘ 맀ν
// i λ³΄λ€ ν° νμμ΄ μλ€λ©΄ ( 0 μΈκ²½μ°λ ν°νμμ΄ μλ κ²½μ°λ€ )
if (adjMatrix[i][0] > 0) {
for (int j = 1; j <= N; j++) {
// cur < i < j==> cur < j
if(adjMatrix[i][j] == 1) {
adjMatrix[cur][j] = 1;
}
}
}
}
}
// κΈ°λ‘ - λ€ λ°°μ΄μ 첫λ²μ§Έ ( 0 )μ λν΄λλ€
int cnt = 0;
for (int i = 1; i <= N; i++) {
cnt += adjMatrix[cur][i];
}
adjMatrix[cur][0] = cnt;
}
}
π€ λμ μκ°
λ¬Έμ νμ΄
μ΄ λ¬Έμ λ κ·Έλνμ λνμ μΈ λ¬Έμ λΌ μ¬λ¬κ°μ§ νμ΄λ²μΌλ‘ μ λ¦¬ν΄ λ³΄μλ€.