My task is the greedy algorithm:
The activity selection problem is characteristic to this class of problems, where the goal is to pick the maximum number of activities that do not clash with each other.
Input and output here:
The program works on small data, but it is too slow for really big input and I don't know how to improve it. Any ideas?
class Program
{
static int N;
static int[,] a;
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(@"prednasky.in"))
{
string line;
line = sr.ReadLine();
N = int.Parse(line);
a = new int[N, 2];
int[] indx = new int[N];
int[] b = new int[N];
for (int i = 0; i < N; i++)
{
line = sr.ReadLine();
int[] nums = line.Trim().Split().Select(w => int.Parse(w)).ToArray();
a[i, 0] = nums[0];
a[i, 1] = i + 1;
b[i] = nums[1];
indx[i] = i;
}
Array.Sort(b, indx);
int last = 0;
int poc = 0;
for (int i = 0; i < N; i++)
{
if (a[indx[i], 0] > last)
{
a[indx[poc], 0] = a[indx[i], 1];
poc++;
last = b[i];
}
}
using (StreamWriter sr1 = new StreamWriter(@"rozvrh.out"))
{
sr1.WriteLine(poc);
for (int i = 0; i < poc; i++)
{
sr1.Write(a[indx[i], 0]);
sr1.Write(" ");
}
}
}
}
}