今年暑假不AC

刚开始的时侯,自己以为最优的解法,先按开始时间排序,如果相同再按照,结束时间排序,然后根据时间差得结果,

可是一直wrong answer,百度了下别人的思路,才知道最优的解法,是按结束时间排序,想想也是.......

贪心就是如何找最优解法。。。。。。。

View Code
1 #include<stdio.h>
2 #include<string.h>
3 #include<stdlib.h>
4 #include<algorithm>
5  using namespace std;
6  struct node
7 {
8 int i;
9 int j;
10
11 }T[1000];
12
13 int cmp(node a,node b)
14 {
15 return a.j<b.j;
16 }
17
18 int main( )
19 {
20 int N;
21 while(scanf("%d",&N)!=EOF)
22 {
23 int i,j,k,m,n,count=0;
24 for(i=0;i<N;i++)
25 {
26 scanf("%d%d",&T[i].i,&T[i].j);
27
28 }
29 sort(T,T+N,cmp);
30 count=1;i=0;
31 //for(i=0;i<N;i++)
32 //printf("%d %d\n",T[i].i,T[i].j);
33 for(j=1;j<N;j++)
34 {
35 if(T[j].i>=T[i].j)
36 {
37 i=j;
38 count++;
39 }
40
41 }
42 printf("%d\n",count);
43 }
44 system("pause");
45 return 0;
46 }
47

网上还有一种按照自己结构体二级排序的,不过是从后面开始的...

View Code
1 #include<stdio.h>
2 #include<string.h>
3 #include<stdlib.h>
4 struct node
5 {
6 int i;
7 int j;
8 int v;
9 }T[1000];
10
11 int cmp(const void *a,const void *b)
12 {
13 if( (*(node *)a).i== (*(node *)b).i )
14 return (*(node *)a).j-(*(node *)b).j;
15 else
16 return (*(node *)a).i-(*(node *)b).i;
17 }
18
19 int cmp(node a,node b)
20 {
21 return a.j<b.j;
22 }
23 int main( )
24 {
25 int N;
26 while(scanf("%d",&N)!=EOF)
27 {
28 int i,j,k,m,n,count=0;
29 for(i=0;i<N;i++)
30 {
31 scanf("%d%d",&T[i].i,&T[i].j);
32 T[i].v=1;
33 }
34 qsort(T,N,sizeof(T[0]),cmp);
35 for (i = N - 2; i >= 0; i--)
36 {
37 for (j = i + 1; j < N; j++)
38 {
39 if (T[i].j <= T[j].i && T[i].v < T[j].v + 1)
40 T[i].v = T[j].v + 1;
41 }
42 if (count< T[i].v)
43 count= T[i].v;
44 }
45
46 printf("%d\n",count);
47 }
48
49 return 0;
50 }
51

posted on 2011-04-24 20:48  more think, more gains  阅读(154)  评论(0编辑  收藏  举报

导航