本题与nyoj 891 找点问题 类似, 都属于贪心算法。
nyoj 891的链接:nyoj 891 找点
解题思路:如果输入的开始时间大于输入结束时间,交换两时间, 然后以结束时间从小到大的顺序进行排序,再以开始时间从小到大的顺序进行排序, 如果后一个的开始时间大于前一个的结束时间,则进行统计, 最后输出统计结果
AC代码:
# include <stdio.h>
# include <algorithm>
struct TIME
{
int h1;
int m1;
int h2;
int m2;
};
int cmp(const void * c, const void * d)
{
TIME * a = (TIME *)c;
TIME * b = (TIME *)d;
if (a->h2 != b->h2)
{
return a->h2 - b->h2;
}
else if (a->m2 != b->m2)
{
return a->m2 - b->m2;
}
else if (a->h1 != b->h1)
{
return a->h1 - b->h1;
}
else if (a->m1 != b->m1)
{
return a->m1 - b->m1;
}
}
int main(void)
{
TIME t[105];
int n;
while (scanf("%d", &n) != EOF)
{
int i;
for (i = 0; i < n; i++)
{
scanf("%d:%d-%d:%d", &t[i].h1, &t[i].m1, &t[i].h2, &t[i].m2);
if (t[i].h2 < t[i].h1)
{
int t1 = t[i].h2;
t[i].h2 = t[i].h1;
t[i].h1 = t1;
int t2 = t[i].m2;
t[i].m2 = t[i].m1;
t[i].m1 = t2;
}
else if (t[i].h2 == t[i].h1 && t[i].m2 < t[i].m1)
{
int t3 = t[i].m1;
t[i].m1 = t[i].m2;
t[i].m2 = t3;
}
}
qsort(t, n, sizeof(t[0]), cmp);
int th2 = t[0].h2;
int tm2 = t[0].m2;
int count = 1;
for (i = 1; i < n; i++)
{
if (t[i].h1 > th2)
{
count ++;
th2 = t[i].h2;
tm2 = t[i].m2;
}
else if (t[i].h1 == th2 && t[i].m1 > tm2)
{
count ++;
th2 = t[i].h2;
tm2 = t[i].m2;
}
}
printf("%d\n", count);
}
return 0;
}