搜狗编程题
发布于 2017-09-28 21:57 1870 次浏览 0 赞 来自 试题交流  

import sys
tp="0"
num=0
a=[]
while True:
    tp=raw_input()
    if tp:
        for ttp in tp.split():
            try:
                a.append(float(ttp))
                num+=1
            except ValueError:
                pass
    else:
        break
    
for i in range(0,num):
    temp1=a[i]
    for j in range(i+1,num):
        if(a[j]<temp1):
            temp1=a[j]
    a[i]=temp1
    print temp1
    

count=0
for i in range(0,num):
    for j in range(i+1,num):
        cha=a[j]-a[i]
        if(cha==180):
            continue
        if(cha<180):
            count+=j-i-1
            continue
        if(cha>180):
            count+=i+num-j-1
            continue
print count

真蛋疼,我输入那块儿一直报错

总的思想是先排序,然后比较任意两个点的角度差,然后判断这两个点之间的劣弧上有多少个点,计数。

总的时间复杂度O(n`2)

2 条回复

O(n^2)的话,我用c++运行了50%的测试用例之后就超时了,应该有更优的方法。哪位大神出来说下,是不是应该用些数据结构

2017-09-28 22:38

用二分,但是我也只对了80%,求大神瞧瞧

package test;

import java.util.Scanner;

public class _搜狐 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		float[] a = new float[n];
		for(int i=0;i<n;i++) {
			a[i] = in.nextFloat();
		}
        //a[n]=(float)360;
		long ans = 0;
		for(int i=0;i<n;i++) {
			
			int t;
            if((a[i]+(float)180)>360) {
				float tmp = (a[i]-(float)180);
				System.out.println("---:"+lower_bound(a, tmp, 0, n-1));
				t = lower_bound(a, tmp, 0, n-1)+(n-i-1);
			}
			else {
				System.out.println("--+-:"+lower_bound(a, a[i]+(float)180, 0, n-1));
				t = lower_bound(a, (a[i]+(float)180), 0, n-1)-i-1;
			}
			System.out.println("++++++:"+t);
			if(t>1) {
				ans += (long)t*(t-1)/2;
			}
		}
		System.out.println(ans);
	}
	public static int lower_bound(float[] d,float x,int l,int r){
		int m;
		while(l<r){
			m = (l+r)>>1;
			if(d[m]>=x) r=m;
			else l=m+1;
		}
		return l;
	}
}


2017-10-01 21:02
添加回复
回到顶部