Algorithm to calculate number of intersecting discs

前端 未结 30 1495
鱼传尺愫
鱼传尺愫 2020-12-12 10:57

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius

30条回答
  •  抹茶落季
    2020-12-12 11:49

    100% score in Codility.

    Here is an adaptation to C# of Толя solution:

        public int solution(int[] A)
        {
            long result = 0;
            Dictionary dps = new Dictionary();
            Dictionary dpe = new Dictionary();
    
            for (int i = 0; i < A.Length; i++)
            {
                Inc(dps, Math.Max(0, i - A[i]));
                Inc(dpe, Math.Min(A.Length - 1, i + A[i]));
            }
    
            long t = 0;
            for (int i = 0; i < A.Length; i++)
            {
                int value;
                if (dps.TryGetValue(i, out value))
                {
                    result += t * value;
                    result += value * (value - 1) / 2;
                    t += value;
                    if (result > 10000000)
                        return -1;
                }
                dpe.TryGetValue(i, out value);
                t -= value;
            }
    
            return (int)result;
        }
    
        private static void Inc(Dictionary values, long index)
        {
            int value;
            values.TryGetValue(index, out value);
            values[index] = ++value;
        }
    

提交回复
热议问题