poj:4091:The Closest M Points,poj4091

來源:互聯網
上載者:User

poj:4091:The Closest M Points,poj4091
poj:4091:The Closest M Points
題目

描述

每到飯點,就又到了一日幾度的小L糾結去哪吃飯的時候了。因為有太多太多好吃的地方可以去吃,而小L又比較懶不想走太遠,所以小L會先找到距離他最近的M家餐館然後再做篩選。

小L現在所在的位置和每家餐館的位置用同一笛卡爾座標系中的點表示,而點與點之間的距離為歐幾裡得距離,對於點p = (p1, p2,..., pn)和點q = (q1,q2,..., qn),兩者的距離定義如下

現給出在K維空間中小L所處的位置的座標以及n個餐館的位置,請協助小L完成他的需求。


輸入
第1行包含兩個整數n和K,1≤n≤5000,1≤K≤5。
接下來n行,每行包含K個數,表示每個餐館的座標。
接下來1行,包含一個數t,1≤t≤10000,表示小L詢問的數目。
每次詢問包括兩行。第1行包含K個數,表示小L所在的座標。第2行包含一個數M,1≤M≤10。
所有座標值不會超過10000。
輸入資料包含多組資料,請逐個處理直到檔案結束。
輸出
對於每一個詢問,輸出m+1行:
第1行輸出:”the closest M points are:”,其中M在輸入中給出。
接下來M行輸出距離最近的M家餐館的座標,按照由近及遠的順序輸出。
輸出資料保證答案唯一。保證從小L的位置到最近的M+1家餐館位置各不相同,這說明如下輸入資料:
2 2
1 1
3 3
1
2 2
1
不會存在。
範例輸入
3 21 11 33 422 322 31
範例輸出
the closest 2 points are:1 33 4the closest 1 points are:1 3
解題方案,這個題目比較簡單我們轉換問題這是求出k最大值或者最小值問題暴力法是先排序再求出前m個最小值快捷法是建立m規模的小頂堆,然後去所有資料去更新一邊,最後所有的堆的元素就是結果
代碼(暴力法代碼)
#include <iostream>#include <fstream>#include <list>#include <math.h>#include <algorithm>using namespace std;typedef pair<double,int> distance_restaurant;void read_data();// data 為餐館地址表list<distance_restaurant> main_solution(int ** data,int n,int k,int *dizhi);int main(){read_data();system("pause");return 0;}void read_data(){ifstream reader;reader.open("data.txt");int n,k;reader>>n;reader>>k;int ** data = new int *[n];for( int i=0; i<n; i++ ){data[i] = new int[k];for(int j=0;j<k;j++)reader>>data[i][j];}int t;reader>>t;while( t>0 ){t-- ;int * dizhi = new int[k] ;for( int i=0;i<k;i++ )reader>>dizhi[i] ;int m;reader>>m;cout<<"the closest "<<m<<" points are:"<<endl;list<distance_restaurant> result = main_solution(data,n,k,dizhi);for( list<distance_restaurant>::iterator it = result.begin();m>0 && it != result.end() ;m-- ,it++){for(int j=0;j<k;j++){cout<<data[it->second][j]<<" ";}cout<<endl;}}}// data 為餐館地址表list<distance_restaurant> main_solution(int ** data,int n,int k,int *dizhi){list<distance_restaurant> result;distance_restaurant elem;for( int i=0;i<n;i++){elem.second = i;elem.first = 0;for(int j=0;j<k;j++){elem.first += (data[i][j]-dizhi[j]) * (data[i][j]-dizhi[j]);}elem.first = sqrt(elem.first);result.push_back(elem);}stable_sort(result.begin(),result.end());return result;}




poj1470所有測試案例都通過,為何提交時總是提示wrong answer,代碼如下,幫忙看一看的:

你這個演算法有問題吧...別人問的是Closest Common Ancestors ,Common Ancestors 有很多啊
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.