Exemplo n.º 1
0
        public int Solve()
        {
            var bitree = new BITree(n + 1);

            int[] pos = new int[n + 1];
            for (int i = 0; i < n; i++)
            {
                var x = ns[i];
                pos[x] = i + 1;
            }

            int ans = 0;

            for (int i = 1; i <= n; i++)
            {
                int s = bitree.Sum(pos[i], n);
                if (s > MAX_BRIBING_NUM)
                {
                    return(-1);
                }
                bitree.Add(pos[i], 1);
                ans += s;
            }
            return(ans);
        }
Exemplo n.º 2
0
    public static int GetInversionNumber(string input)
    {
        List <NumberNode> numberList = new List <NumberNode>(input.Length);

        //离散化过程
        for (int i = 0, length = input.Length; i < length; ++i)
        {
            numberList.Add(new NumberNode()
            {
                value = int.Parse(input[i].ToString()),
                order = i
            });
        }

        numberList.Sort(((node1, node2) =>
        {
            return(node1.value.CompareTo(node2.value));
        }));

        int[] values = new int[input.Length];
        for (int i = 0, count = numberList.Count; i < count; ++i)
        {
            values[numberList[i].order] = i + 1;
        }

        //树状数组处理过程
        BITree biTree       = new BITree(input.Length);
        int    inversionNum = 0;

        for (int i = 0, length = values.Length; i < length; ++i)
        {
            biTree.Add(values[i], 1);
            inversionNum += i + 1 - biTree.Sum(values[i]);
        }

        return(inversionNum);
    }