Ejemplo n.º 1
0
    Natural CountPath(City city)
    {
        if (city.HasValue())
        {
            return(city.PathCount);
        }

        if (visited[city])
        {
            // a cycle
            foreach (City c in visitedCities)
            {
                // if any of the city in the cycle can reach warfare capital, then there's infinite path, otherwise 0
                bool reachable = IsReachable(c, lastCity);
                if (reachable)
                {
                    return(Natural.Infinity);
                }
                if (c == city)
                {
                    break;
                }
            }
            return(0);
        }

        visited[city] = true;
        visitedCities.Push(city);
        ICollection <City> neighbours = city.Neighbours;

        Natural totalCount = city == lastCity ? 1 : 0;

        foreach (City n in neighbours)
        {
            totalCount = (totalCount + CountPath(n)) % MOD;
            if (totalCount.IsInfinity())
            {
                break;
            }
        }

        visitedCities.Pop();
        visited[city] = false;

        city.PathCount = totalCount;

        return(totalCount);
    }
Ejemplo n.º 2
0
    void Run(TextReader rd)
    {
        string[] ln = rd.ReadLine().Split(' ');
        N             = int.Parse(ln[0]);
        M             = int.Parse(ln[1]);
        visited       = new bool[N + 1];
        visited2      = new bool[N + 1];
        visitedCities = new Stack <City>(N);
        cities        = new City[N + 1];
        reachabletb   = new int[N + 1];

        for (int i = N; i > 0; i--)
        {
            City c = new City(i);
            cities[i] = c;
        }

        firstCity = cities[1];
        lastCity  = cities[N];

        for (int i = 0; i < M; i++)
        {
            ln = rd.ReadLine().Split(' ');
            int from = int.Parse(ln[0]);
            int to   = int.Parse(ln[1]);
            cities[from].Add(cities[to]);
        }

        rd.Dispose();

        Natural count = CountPath(firstCity);

        if (count.IsInfinity())
        {
            Console.WriteLine("INFINITE PATHS");
        }
        else
        {
            Console.WriteLine(count);
        }
    }