poj1828

poj1828

【问题的描述】是这样的:程序猿的近亲 猴子(......)最近在进行王位争夺站。

题中使用二维坐标轴上的点(x,y)来代表猴子所占有的位置,

每只猴子占有一个坐标点。并且一个坐标点上面有且只有一个猴子。

如果说一直猴子是王位的继承者的话,那么这只猴子所占有的坐标(x0,y0)必须满足这样的一个条件:

一定不存在这样的一个坐标点(xi,yi)使得(xi >= x0)  and (yi >= yo).

下面需要你用程序来实现在众多组(case)二维坐标数值(x,y)中选取出

该组(case)的有可能为猴王的猴子数目的总数目。结束输入用0来表示。

输入样例:

3
2 1
1 2
3 3
3
0 1
1 0
0 0
4
0 0
1 0
0 1
1 1
0

输出样例:

1
2
1

【算法描述:】

最近才知道,对于测试case数目不一定的情况,可以用结束标志(此题为0)来做为判断循环条件,

针对一组case数据输入,跑一次算法,然后得出一个输出结果,然后将其提交给poj。

如此下来如果结果是正确的话,poj服务器端也是会AC的(好吧,这是LZ最近才知道的....)。

伪代码:

typedef struct 
{
     int x;
     int y;  
}monkey;


int cmp_x(a, b)
{
    monkey *m1,*m2;

     m1<-  (monkey*)a;
    m2 <-  (monkey*)b


  if  m1->x != m2->x
       return m2->x - m1->x;
 else
       return m2->y -m1->y;

  
}//used in inverse qsort   large -> small



monkey Monkey[50000];

while(~scanf( n )  && n !=0)
{
       for(i   0 -> n-1)
        {
              scanf(Monkey[i],x,  Monkey[i].y);
         }

         qsort(Monkey, n, sizeof(monkey), cmp);
//after this sort  the x (large -> small)
//and if the value of the x equal , then the value of y (large -> small)

    

    num =1;//this is use to count how many kings in the input test case
    
   maxY = monkey[0].y;     
       
     for(i   1->n-1)
       {
            if(maxY > monkey[i].y)
            {
                 num++;
                 maxY = monkey[i].y;
            }
       }
   
     printf  (num);  

}

 【实现代码:为以后优化代码作参照比对】

#include<stdio.h>
#include<algorithm>

typedef struct
{
    int x;
    int y;
}monkey;


monkey Monkey[50000];
//this is for test

int cmp_x(const void *a, const void *b)
{
    monkey *m1,*m2;
    m1 = (monkey*)a;
    m2 = (monkey*)b;

    if(m1->x!=m2->x)
        return m2->x - m1->x;
    else
        return m2->y - m1->y;
}

int main()
{
    int n;
    int i;
    int num, maxY;

    while(~scanf("%d", &n) && n!=0)
    {

        for(i = 0; i <n; i++)
        {
            scanf("%d %d", &Monkey[i].x, &Monkey[i].y );
        }


        qsort(Monkey, n, sizeof(monkey), cmp_x);

        num = 1;
        maxY = Monkey[0].y;

        for(i = 1 ; i < n; i++)
        {
            if(Monkey[i].y  > maxY)
            {
                maxY = Monkey[i].y;
                num++;
            }
        }

        printf("%d
", num);
    }
    

}

可以看一下注释哪一行:

this is for test,因为目前做的题比较少,阅读的代码量也不是很多。

【学习总结:】每当看到别人的代码大批大批静态分配空间的时候,总是很不理解。

但是这次,LZ使用了malloc进行动态分配内存的方式,每次根据输入的n数值开辟对应的n个monkey空间。

结果优化的策略全部泡汤,时间,空间,代码量全部上升。 

就目前的水平,一时半会很难找到适合的代替qsort的方法

本想用并查集来解决该问题的,目前暂时的想法是这样的:

makeSet,findSet的基本实现方法是不用做太多调整的。

而对于unionSet这一个方法就不能简单地从判断矢量高度或是集合中元素的个数来对传入的两个数据进行二者所在集合的合并。

这个还没有想好,或是从问题的条件设定根本行不通,就先放在这里吧。呵呵~

------------ 能改变现状的,只有战斗的觉悟 ------------
原文地址:https://www.cnblogs.com/inuyasha1027/p/ACM_src.html