AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC170-D Not Divisible


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("5");
            WillReturn.Add("24 11 8 3 16");
            //3
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("4");
            WillReturn.Add("5 5 5 5");
            //0
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("10");
            WillReturn.Add("33 18 45 28 8 19 89 86 2 4");
            //5
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        var CntDict = new Dictionary<long, long>();
        foreach (var Query in AArr.GroupBy(pX => pX)) {
            CntDict[Query.Key] = Query.Count();
        }

        long MaxVal = CntDict.Keys.Max();
        long UB = MaxVal;

        bool[] IsBaisuuArr = new bool[UB + 1];

        long Answer = 0;
        foreach (var EachPair in CntDict.OrderBy(pX => pX.Key)) {
            if (EachPair.Value == 1) {
                if (IsBaisuuArr[EachPair.Key] == false) {
                    Answer++;
                }
            }

            for (long I = EachPair.Key; I <= UB; I += EachPair.Key) {
                IsBaisuuArr[I] = true;
            }
        }
        Console.WriteLine(Answer);
    }
}


解説

エラトステネスの篩のアルゴリズムを応用してます。