# C# greedy algorithm to pick activities that do not clash with each other

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)

{
{
string line;
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++)
{
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(" ");
}
}
}
}
}

• Is that how you really didn't indent your code? The easiest way to post code is to paste it, highlight it, and press Ctrl-K to mark it as a code block. Mar 9, 2017 at 5:13
• Follow-up question Mar 9, 2017 at 20:14

Step 1 is to indent your code, because it's very difficult to read if it's not indented:

class Program
{
static int N;
static int[,] a;

static void Main(string[] args)

{
{
string line;
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++)
{
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(" ");
}
}
}
}
}


• I don't see any reason for N and a to be static class members instead of local variables.
• I can't tell what the variable a is supposed to represent. Can it be given a more descriptive name?