zoukankan      html  css  js  c++  java
  • K points to origin

    Given a bounch of points, ask to find K closest point to origin. 

    This question can be changed. For example, here is origin, but there might be another point. 

    Here is just a basic algorithm.

    //  main.cpp

    //  k points to origin

    //  Created by Xiaohe Huang on 10/19/15.

    //  Copyright © 2015 Xiaohe Huang. All rights reserved.

    //

    #include <iostream>

    #include<algorithm>

    #include<queue>

    using namespace std;

    struct Cpoint

    {

        double x;

        double y;

    };

    struct cmp

    {

    public:

        bool operator()(Cpoint n1,Cpoint n2)

        {

            return (n1.x)*(n1.x)+(n1.y)*(n1.y)<(n2.x)*(n2.x)+(n2.y)*(n2.y);

        }

    };

    int main(int argc, const char * argv[]) {

        // insert code here...

        Cpoint points[5];

        points[0]={9,9};

        points[1]={8,8};

        points[2]={7,7};

        points[3]={6,6};

        points[4]={5,5};

        priority_queue<Cpoint,vector<Cpoint>,cmp> pq;

        for(int i;i<5;i++)

        {

            if(i<3)

                pq.push(points[i]);

            else

            {

                if((points[i].x)*(points[i].x)+(points[i].y)+(points[i].y)<(pq.top().x+pq.top().x)+(pq.top().y+pq.top().y))

                {

                    pq.pop();

                    pq.push(points[i]);

                }

            }

        }

         return 0;

    }

  • 相关阅读:
    volatile关键字解析(转载)
    php
    FFT快速傅立叶变换
    高次不定方程BSGS算法
    BSGS-BabyStepGiantStep算法+拓展
    Java-数组-面向对象
    Java基础-方法(2)和数组
    Java基础-循环(2)和方法
    Java基础-循环结构
    Java基础-运算符
  • 原文地址:https://www.cnblogs.com/CathyXiaohe/p/4985284.html
Copyright © 2011-2022 走看看