Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Contest
- {
- internal class Edge
- {
- public int From { get; set; }
- public int To { get; set; }
- public int Cost { get; set; }
- public Edge(int @from, int to, int cost)
- {
- From = @from;
- To = to;
- Cost = cost;
- }
- }
- internal class Graph
- {
- private List<Edge> _edges;
- private int _n;
- private int _m;
- public Graph(int n, int m)
- {
- _edges = new List<Edge>();
- _n = n;
- _m = m;
- }
- public void Add(Edge edge)
- {
- _edges.Add(edge);
- }
- private static List<T> FillList<T>(int count, T value = default)
- {
- var result = new List<T>(count);
- for (var i = 0; i < count; i++)
- {
- result.Add(value);
- }
- return result;
- }
- public IList<int> GetNegativeCycle()
- {
- var distance = FillList<int>(_n);
- var parents = FillList(_n, -1);
- var negativeChecker = -1;
- for (var i = 0; i < _n; i++)
- {
- negativeChecker = -1;
- for (var j = 0; j < _m; j++)
- {
- if (distance[_edges[j].To] > distance[_edges[j].From] + _edges[j].Cost)
- {
- distance[_edges[j].To] = Math.Max(int.MinValue, distance[_edges[j].From] + _edges[j].Cost);
- parents[_edges[j].To] = _edges[j].From;
- negativeChecker = _edges[j].To;
- }
- }
- }
- if (negativeChecker == -1)
- return null;
- var parent = negativeChecker;
- for (var i = 0; i < _n; i++)
- parent = parents[parent];
- var path = new List<int>();
- for (var current = parent; ; current = parents[current])
- {
- path.Add(current + 1);
- if (current == parent && path.Count > 1)
- break;
- }
- path.Reverse();
- return path;
- }
- }
- internal class Program
- {
- private static int[] ReadArgs()
- {
- return Console.ReadLine()
- .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(int.Parse)
- .ToArray();
- }
- private static void Main()
- {
- var args = ReadArgs();
- int n = args[0], m = args[1];
- var graph = new Graph(n, m);
- for (var i = 0; i < m; i++)
- {
- args = ReadArgs();
- var edge = new Edge(args[0] - 1, args[1] - 1, args[2]);
- graph.Add(edge);
- }
- var negativeCycle = graph.GetNegativeCycle();
- if (negativeCycle == null)
- Console.WriteLine(-1);
- else
- {
- Console.WriteLine($"1\n{negativeCycle.Count - 1}");
- var output = string.Join(" ", negativeCycle);
- Console.WriteLine(output);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement