SMALL
https://www.acmicpc.net/problem/18352
18352번: 특정 거리의 도시 찾기
첫째 줄에 도시의 개수 N, 도로의 개수 M, 거리 정보 K, 출발 도시의 번호 X가 주어진다. (2 ≤ N ≤ 300,000, 1 ≤ M ≤ 1,000,000, 1 ≤ K ≤ 300,000, 1 ≤ X ≤ N) 둘째 줄부터 M개의 줄에 걸쳐서 두 개
www.acmicpc.net
- 문제
- 문제풀이
BFS를 시행해주고 각 BFS마다 카운트를 해주어 비교해준다.
- 코드 1
namespace YONGYONG2
{
using System;
using System.Collections.Generic;
using System.Text;
public class Program
{
static int N;
static int X;
static int K;
static bool[] BFSbool;
static int[] bfscount;
static bool Print;
static List<int>[] graph;
public static void BFS(int V)
{
Queue<int> queue = new Queue<int>();
queue.Enqueue(V);
BFSbool[V] = true;
while (queue.Count > 0)
{
int temp = queue.Dequeue();
foreach (int next in graph[temp])
{
if (!BFSbool[next])
{
BFSbool[next] = true;
queue.Enqueue(next);
bfscount[next] = bfscount[temp] + 1;
if (bfscount[next] == K)
{
Print = true;
}
}
}
}
if (Print)
{
for(int i=1;i<N+1;i++)
{
if (bfscount[i] == K)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine(-1);
}
}
public static void Main(string[] args)
{
string[] input = Console.ReadLine().Split();
N = int.Parse(input[0]);
int M = int.Parse(input[1]);
K = int.Parse(input[2]);
X = int.Parse(input[3]);
graph = new List<int>[N + 1];
for (int i = 1; i <= N; i++)
{
graph[i] = new List<int>();
}
BFSbool = new bool[N + 1];
bfscount = new int[N + 1];
for (int i = 0; i < M; i++)
{
string[] line = Console.ReadLine().Split();
int a = int.Parse(line[0]);
int b = int.Parse(line[1]);
graph[a].Add(b);
}
for (int i = 1; i <= N; i++)
{
graph[i].Sort();
}
bfscount[X] = 0;
BFS(X);
}
}
}
- 후기
카운트를 비교해주는 과정이 어려웠다.
LIST
'백준 > C#' 카테고리의 다른 글
[C#]백준 10809번: 알파벳 찾기 (2) | 2023.03.13 |
---|---|
[C#]백준 2252번: 줄 세우기 (0) | 2023.03.08 |
[C#]백준 9372번: 상근이의 여행 (0) | 2023.03.06 |
[C#]백준 24480: 알고리즘 수업 - 너비 우선 탐색 2 (0) | 2023.03.06 |
[C#]백준 24480: 알고리즘 수업 - 깊이 우선 탐색 2 (0) | 2023.03.06 |