競技プログラミングの鉄則    次の問題へ    前の問題へ

A39 Interval Scheduling Problem


問題へのリンク


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("3");
            WillReturn.Add("123 86399");
            WillReturn.Add("1 86400");
            WillReturn.Add("86399 86400");
            //2
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    struct LRInfoDef
    {
        internal int L;
        internal int R;
    }
    static List<LRInfoDef> mLRInfoList = new List<LRInfoDef>();

    static void Main()
    {
        List<string> InputList = GetInputList();

        int[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();

        foreach (string EachStr in InputList.Skip(1)) {
            SplitAct(EachStr);
            LRInfoDef WillAdd;
            WillAdd.L = wkArr[0];
            WillAdd.R = wkArr[1];
            mLRInfoList.Add(WillAdd);
        }

        mLRInfoList = mLRInfoList.OrderBy(pX => pX.R).ToList();

        int Answer = 0;
        int CurrTime = 0;
        foreach (LRInfoDef EachLRInfo in mLRInfoList) {
            if (CurrTime <= EachLRInfo.L) {
                Answer++;
                CurrTime = EachLRInfo.R;
            }
        }
        Console.WriteLine(Answer);
    }
}


解説

区間Endの昇順に、区間を採用してます。