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:
enter image description 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(" ");
}
}
}
}
}
-
3\$\begingroup\$ 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. \$\endgroup\$200_success– 200_success2017年03月09日 05:13:50 +00:00Commented Mar 9, 2017 at 5:13
-
\$\begingroup\$ Follow-up question \$\endgroup\$200_success– 200_success2017年03月09日 20:14:30 +00:00Commented Mar 9, 2017 at 20:14
1 Answer 1
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)
{
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(" ");
}
}
}
}
}
A couple of comments:
- I don't see any reason for
N
anda
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? - Your code doesn't have any comments explaining the algorithm you're implementing. Those would be helpful for understanding the code.