using
System;
using
System.Collections.Generic;
public
class
MainClass
{
static
int
Dijkstra(
int
N,
int
P, List<List<
int
>> adj)
{
int
[] dist =
new
int
[N + 1];
bool
[] vis =
new
bool
[N + 1];
PriorityQueue<(
int
,
int
)> pq =
new
PriorityQueue<(
int
,
int
)>(
new
MaxMinComparer());
dist[P] = P;
pq.Enqueue((P, P));
while
(pq.Count > 0)
{
(
int
dis,
int
u) = pq.Dequeue();
if
(vis[u])
continue
;
vis[u] =
true
;
foreach
(
int
v
in
adj[u])
{
int
d = Math.Min(dis, v);
if
(dist[v] < d)
{
dist[v] = d;
pq.Enqueue((d, v));
}
}
}
int
count = 0;
for
(
int
i = 1; i <= N; i++)
{
if
(i <= dist[i])
count++;
}
return
count;
}
static
void
Solve(
int
N,
int
M,
int
P, List<List<
int
>> edges)
{
List<List<
int
>> adj =
new
List<List<
int
>>();
for
(
int
i = 0; i <= N; i++)
{
adj.Add(
new
List<
int
>());
}
foreach
(List<
int
> edge
in
edges)
{
int
u = edge[0];
int
v = edge[1];
adj[u].Add(v);
adj[v].Add(u);
}
int
filledVertices = Dijkstra(N, P, adj);
Console.WriteLine(
"Number of filled vertices are: "
+ filledVertices);
}
public
static
void
Main(
string
[] args)
{
int
N = 4, M = 4, P = 4;
List<List<
int
>> edges =
new
List<List<
int
>>
{
new
List<
int
> { 1, 3 },
new
List<
int
> { 1, 4 },
new
List<
int
> { 2, 3 },
new
List<
int
> { 2, 4 }
};
Solve(N, M, P, edges);
}
}
public
class
MaxMinComparer : IComparer<(
int
,
int
)>
{
public
int
Compare((
int
,
int
) x, (
int
,
int
) y)
{
return
y.Item1.CompareTo(x.Item1);
}
}
public
class
PriorityQueue<T>
{
private
readonly
List<T> heap;
private
readonly
IComparer<T> comparer;
public
PriorityQueue() :
this
(Comparer<T>.Default)
{
}
public
PriorityQueue(IComparer<T> comparer)
{
this
.heap =
new
List<T>();
this
.comparer = comparer;
}
public
int
Count => heap.Count;
public
void
Enqueue(T item)
{
heap.Add(item);
int
i = heap.Count - 1;
while
(i > 0)
{
int
parent = (i - 1) / 2;
if
(comparer.Compare(heap[parent], item) >= 0)
break
;
heap[i] = heap[parent];
i = parent;
}
heap[i] = item;
}
public
T Dequeue()
{
int
n = heap.Count - 1;
T result = heap[0];
T item = heap[n];
heap.RemoveAt(n);
if
(n == 0)
return
result;
int
i = 0;
while
(
true
)
{
int
left = i * 2 + 1;
if
(left >= n)
break
;
int
right = left + 1;
int
child = (right >= n || comparer.Compare(heap[left], heap[right]) >= 0) ? left : right;
if
(comparer.Compare(item, heap[child]) >= 0)
break
;
heap[i] = heap[child];
i = child;
}
heap[i] = item;
return
result;
}
public
T Peek()
{
return
heap[0];
}
}