1:距離排序_資料結構與演算法

來源:互聯網
上載者:User
總時間限制:  1000ms  記憶體限制:  65536kB 描述 給出三維空間中的n個點(不超過10個),求出n個點兩兩之間的距離,並按距離由大到小依次輸出兩個點的座標及它們之間的距離。
輸入 輸入包括兩行,第一行包含一個整數n表示點的個數,第二行包含每個點的座標(座標都是整數)。 點的座標的範圍是0到100,輸入資料中不存在座標相同的點。 輸出 對於大小為n的輸入資料,輸出 n*(n-1)/2行格式如下的距離資訊:
(x1,y1,z1)-(x2,y2,z2)=距離
其中 距離保留到數點後面2位。
(用cout輸出時保留到小數點後2位的方法:cout<<fixed<<setprecision(2)<<x) 範例輸入
40 0 0 1 0 0 1 1 0 1 1 1
範例輸出
(0,0,0)-(1,1,1)=1.73(0,0,0)-(1,1,0)=1.41(1,0,0)-(1,1,1)=1.41(0,0,0)-(1,0,0)=1.00(1,0,0)-(1,1,0)=1.00(1,1,0)-(1,1,1)=1.00
提示 用cout輸出時保留到小數點後2位的方法:cout<<fixed<<setprecision(2)<<x

注意:
冒泡排序滿足下面的性質,選擇排序和快速排序(qsort或sort)需要對下面的情況進行額外處理
使用冒泡排序時要注意邊界情況的處理,保證比較的兩個數都在數組範圍內
1. 對於一行輸出中的兩個點(x1,y1,z1)和(x2,y2,z2),點(x1,y1,z1)在輸入資料中應出現在點(x2,y2,z2)的前面。
比如輸入:
2
0 0 0 1 1 1
輸出是:
(0,0,0)-(1,1,1)=1.73
但是如果輸入:
2
1 1 1 0 0 0
輸出應該是:
(1,1,1)-(0,0,0)=1.73

2. 如果有兩對點p1,p2和p3,p4的距離相同,則先輸出在輸入資料中靠前的點對。
比如輸入:
3
0 0 0 0 0 1 0 0 2
輸出是:
(0,0,0)-(0,0,2)=2.00
(0,0,0)-(0,0,1)=1.00
(0,0,1)-(0,0,2)=1.00
如果輸入變成:
3
0 0 2 0 0 1 0 0 0
則輸出應該是:
(0,0,2)-(0,0,0)=2.00
(0,0,2)-(0,0,1)=1.00
(0,0,1)-(0,0,0)=1.00

調用庫函數。又是偷懶。
#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>#include<assert.h>#include<ctype.h>#include<stdlib.h>#include<math.h>using namespace std;struct point{    int x,y,z;}P[200];struct ANS{    int h1,h2;    double juli;}J[10100];double ce(point a1,point a2){    return sqrt((a1.x-a2.x)*(a1.x-a2.x)+(a1.y-a2.y)*(a1.y-a2.y)+(a1.z-a2.z)*(a1.z-a2.z));}bool cmp(ANS a1,ANS a2){    if(a1.juli!=a2.juli)return a1.juli>a2.juli;    else if(a1.h1!=a2.h1)return a1.h1<a2.h1;    else return a1.h2<a2.h2;}int main(){//freopen("in.txt","r",stdin);//freopen("out.txt","w",stdout);    int n;    scanf("%d",&n);    int i=0;    for(i=0;i<n;i++)    {        scanf("%d%d%d",&P[i].x,&P[i].y,&P[i].z);    }    int j;    int cnt=0;    for(i=0;i<n;i++)        for(j=i+1;j<n;j++)        {            J[cnt].h1 = i;            J[cnt].h2 = j;            J[cnt++].juli = ce(P[i],P[j]);        }        sort(J,J+cnt,cmp);        for(i=0;i<cnt;i++)        {            printf("(%d,%d,%d)-(%d,%d,%d)=%.2lf\n",P[J[i].h1].x,P[J[i].h1].y,P[J[i].h1].z,P[J[i].h2].x,P[J[i].h2].y,P[J[i].h2].z,J[i].juli);        }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.