TLE on CSES BUILDING ROADS HAVE USE DFS

please help me out i used the stack and fast scanner also
sol link-https://cses.fi/paste/cc989c0ccbfe2f2a10c465/
prob link-https://cses.fi/problemset/task/1666/

i am not able to find the mistake just 3 case are giving the with almost same input
https://cses.fi/problemset/result/1100597/
please look into it

see the tc 7 and 8

i was doing mistake in stack i got it