1 / 6

向量距离问题

向量距离问题. 解题报告 ------- 郭智强 060320071. 向量距离问题. 对于给定的 m 个整数 a 1 , a 2 ,… a i … a m 组成的向量 A , | a i | <=m ,和另一个由 n 个整数 组成的向量 B , b 1 , b 2 ,… b i … b n | b i | <=n, 试设计一个 O (m +n) 时间算法, 计算给定向量 A 和 B 的距离 dist 。. 算法思想.

maja
Download Presentation

向量距离问题

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 向量距离问题 解题报告 -------郭智强 060320071

  2. 向量距离问题 对于给定的m 个整数a1 ,a2,… ai …am组成的向量A, |ai |<=m,和另一个由n个整数 组成的向量B, b1 ,b2,… bi…bn |bi |<=n,试设计一个O (m+n) 时间算法, 计算给定向量A和B的距离dist。

  3. 算法思想 • 首先,输入m,n.定义三个long类型数组a[],b[],c[].且三个数组的长度都取2*len+1,len=max{m,n}. • c[]数组存取{-len,-len+1…,len}的数,a[]和b[]数组设初始值为0. • 输入m个A向量的数anum,每输入一个数anum,使a[anum+len]++.同样,输入n个B向量的数bnum,每输入一个数bum,使b[bnum+len]++.

  4. 设置at和bt的初值为false,用于标记扫描的时候A和B向量里的数是不是都有出现过.设置min的初值为n+m.设置at和bt的初值为false,用于标记扫描的时候A和B向量里的数是不是都有出现过.设置min的初值为n+m. • For(i=0  2*len) • 判断c[i]这个数有没有在A向量内,有的话,使at=true,并且记下a1=c[i]. • 判断有没有c[i]这个数有没有在B向量内,有的话,使bt=true,并且记下b1=c[i]. • 判断at和bt是否都为真,并且c[i]有在向量A或向量B内,若有的话则计算dist=|a1-b1|; If(min>dist)min=dist;

  5. m=5 A( -5 3 -5 2 4 ) n=5 B(-2 -3 -2 -3 -1) i 0 1 2 3 4 5 6 7 8 9 10 c[i] -5 -4 -3 -2 -1 0 1 2 3 4 5 a[i] 0 0 0 0 0 0 0 0 0 0 0 b[i] 0 0 0 0 0 0 0 0 0 0 0 if(a[i]>0) {a1=c[i];at=true;} if(b[i]>0) {b1=c[i];bt=true;} if(at&&bt&&(a[i]>0||b[i]>0)) {dist=abs(a1-b1);if(min>dist)min=dist;}

  6. 算法复杂度分析 T(n)= 所以时间复杂度为O(m+n)。 O(3m+n)= O (m+n) m>=n O(m+3n)= O (m+n) m<n

More Related