Question H: Watching TV

Question H: Watching TV

Time Limit: 1 Sec   Memory Limit: 32 MB

http://192.168.8.233/problem.php?cid=1061&pid=7

Topic description

The summer vacation is here, and Xiao Ming can finally watch TV happily. But Xiao Ming likes too many programs, and he hopes to see as many complete programs as possible.
Now that he gives you the broadcast schedule of his favorite TV show, can you help him arrange it?

enter

The input contains multiple sets of test data. The first line of each input is an integer n (n<=100), which represents the total number of programs Xiaoming likes.
Next n lines, input two integers si and ei (1<=i<=n) in each line, indicating the start and end time of the i-th program. To simplify the problem, each time is represented by a positive integer.
When n=0, the input ends.

output

For each set of inputs, output the number of TV programs that can be seen in full.

sample input

12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0

Sample output

5

Problem solving ideas

A typical example of greed, it can be found that the end time of each time is arranged from small to large, and then traversed from the first one, if the head is greater than or equal to the tail, +1 is added.

code show as below

                    # include <stdio.h>
struct time
{
	int tail;
	int head;
};
int main(void)
{
	int n, i, sum, c, j;
	struct time a[101], b;
	while (~ scanf("%d", &n))
	{
                if (n == 0)
                break;
                for (i = 0; i < n; i ++)
			scanf("%d %d", &a[i].tail, &a[i].head);
		//sort by end time
		for (i = 0; i < n-1; i ++)
			for (j = i+1; j < n; j ++)
				if (a[i].head > a[j].head)
				{
					b = a[i];
					a[i] = a[j];
					a[j] = b;
				}	
		sum = 1;//The first time is established, so the initial value is 1
		c = 0;
		// Compare the size of the head and tail.
		for (i = 1; i < n; i ++)
		{
			if(a[c].head <= a[i].tail)
			{
				sum ++;
				c = i;
			}
		}
		printf("%d\n", sum);
	}
	return 0;
}
# include <stdio.h>
# include <algorithm>

using namespace std;

struct qwe
{
	int head;
	int tail;
};

bool cmp(struct qwe a, struct qwe b)
{
	return a.head < b.head;
	
}
int main(void)
{
	int n, i, c, k, j;
	struct qwe a[110], t;
	while (~ scanf("%d", &n))
	{
		if (n == 0)
		break;
		for (i = 1; i <= n; i ++)
			scanf("%d %d", &a[i].tail, &a[i].head);
			
		sort(a+1, a+n+1, cmp);
		
		c = 1;
		k = 1;
		for (i = 2; i <= n; i ++)
		{
			if (a[k].head <= a[i].tail)
			{
				c ++;
				k = i;
			}
		}
		printf("%d\n", c);
	}
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325815699&siteId=291194637