C♯の勉強

C♯4.0 で TopCoder の過去問を解きます。

Codeforces Round #204 : Jeff and Periods

namespace Codeforces {
    public class _352B {
        static int? getP(IEnumerable<int> array) {
            if (array.Count() == 1) return 0;
            var diff = array.Zip(array.Skip(1), (a0, a1) => a1 - a0);
            if (diff.Distinct().Count() == 1) return diff.First();
            return null;
        }

        static public void Solve(TextReader cin, TextWriter cout) {
            int n = int.Parse(cin.ReadLine());
            var a = cin.ReadLine().Split().Select(int.Parse).ToArray();

            var lookup = a.Select((v, index) => new { value = v, index })
                .ToLookup(v => v.value, v => v.index);

            var ans = lookup.Select(l => new { x = l.Key, p = getP(l) }).Where(v => v.p != null).ToArray();

            cout.WriteLine(ans.Count());
            foreach (var v in ans.OrderBy(v => v.x)) {
                cout.WriteLine(v.x + " " + v.p);
            }
        }

        public static void Main(string[] args) {
            Solve(Console.In, Console.Out);
        }
    }
}