这题有点意思,勉强可以归于DP吧,跑步时获得的思路,哈哈,写完1A了,思路是对的,略爽,归纳一下就是找出最大的互不相交的线段组,比如[1,2], [2,3]就是两组,而[1,3],[1,2],[2,4],[2,3]都可以归为同一组,先排序预处理一下,然后有O(n)算法可求组,附上两段代码,第一段是初版,内存使用较大,第二段优化了下内存,但时间没怎么变
#include<cstdio>
#include<vector>
#include<cstdlib>
using namespace std;
namespace
{
struct Course
{
int index, begin, end;
} C[100000];
int cmp(const void *p1, const void *p2)
{
struct Course *c1 = (struct Course*) p1;
struct Course *c2 = (struct Course*) p2;
if (c1->begin != c2->begin)
return c1->begin - c2->begin;
else
return c1->end - c2->end;
}
}
int main()
{
int N;
vector<vector<int> > V;
while (scanf("%d", &N) != EOF)
{
for (int i = 0; i < N; i++)
{
C[i].index = i + 1;
scanf("%d %d", &C[i].begin, &C[i].end);
}
qsort(C, N, sizeof(C[0]), cmp);
V.clear();
vector<int> v;
v.push_back(C[0].index);
V.push_back(v);
int end = C[0].end;
for (int i = 1; i < N; i++)
{
if (C[i].end <= end)
{
end = C[i].end;
V.back().push_back(C[i].index);
}
else if (C[i].begin >= end)
{
end = C[i].end;
vector<int> v;
v.push_back(C[i].index);
V.push_back(v);
}
else
{
V.back().push_back(C[i].index);
}
}
printf("%d\n", V.size());
for (size_t i = 0; i < V.size(); i++)
{
for (size_t j = 0; j < V[i].size(); j++)
printf(j ? " %d" : "%d", V[i][j]);
putchar('\n');
V[i].clear();
}
putchar('\n');
}
return 0;
}
#include<cstdio>
#include<cstdlib>
using namespace std;
namespace
{
struct Course
{
int index, begin, end;
} C[100000];
int cmp(const void *p1, const void *p2)
{
struct Course *c1 = (struct Course*) p1;
struct Course *c2 = (struct Course*) p2;
if (c1->begin != c2->begin)
return c1->begin - c2->begin;
else
return c1->end - c2->end;
}
}
int main()
{
int N, S[100000];
while (scanf("%d", &N) != EOF)
{
for (int i = 0; i < N; i++)
{
C[i].index = i + 1;
scanf("%d %d", &C[i].begin, &C[i].end);
}
qsort(C, N, sizeof(C[0]), cmp);
int group = 0;
int end = C[0].end;
for (int i = 1; i < N; i++)
{
if (C[i].end <= end)
end = C[i].end;
else if (C[i].begin >= end)
{
end = C[i].end;
S[group++] = i;
}
}
S[group++] = N;
printf("%d\n", group);
for (int i = 0; i < S[0]; i++)
printf(i == S[0] - 1 ? "%d\n" : "%d ", C[i].index);
for (int i = 1; i < group; i++)
for (int j = S[i - 1]; j < S[i]; j++)
printf(j == S[i] - 1 ? "%d\n" : "%d ", C[j].index);
puts("");
}
return 0;
}