Пример #1
0
 // add all elements to copy of heap
 // takes linear time since already in heap order so no keys move
 public HeapIEnumerator(IndexMaxPQ <Key> maxpq)
 {
     innerPQ = new IndexMaxPQ <Key>(maxpq.Count);
     for (int i = 1; i <= maxpq.N; i++)
     {
         innerPQ.Insert(maxpq.pq[i], maxpq.keys[maxpq.pq[i]]);
     }
     copy = innerPQ;
 }
Пример #2
0
        public static void MainTest(string[] args)
        {
            // insert a bunch of strings
            string[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" };

            IndexMaxPQ <string> pq = new IndexMaxPQ <string>(strings.Length);

            for (int i = 0; i < strings.Length; i++)
            {
                pq.Insert(i, strings[i]);
            }

            // print each key using the iterator
            foreach (int i in pq)
            {
                Console.WriteLine(i + " " + strings[i]);
            }

            Console.WriteLine();

            // increase or decrease the key
            for (int i = 0; i < strings.Length; i++)
            {
                if (StdRandom.Uniform() < 0.5)
                {
                    pq.IncreaseKey(i, strings[i] + strings[i]);
                }
                else
                {
                    pq.DecreaseKey(i, strings[i].Substring(0, 1));
                }
            }

            // delete and print each key
            while (!pq.IsEmpty)
            {
                string key = pq.MaxKey;
                int    i   = pq.DelMax();
                Console.WriteLine(i + " " + key);
            }
            Console.WriteLine();

            // reinsert the same strings
            for (int i = 0; i < strings.Length; i++)
            {
                pq.Insert(i, strings[i]);
            }
            Console.WriteLine("Deleting in randome order");
            // delete them in random order
            int[] perm = new int[strings.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                perm[i] = i;
            }
            StdRandom.Shuffle(perm);
            for (int i = 0; i < perm.Length; i++)
            {
                string key = pq.KeyOf(perm[i]);
                pq.Delete(perm[i]);
                Console.WriteLine(perm[i] + " " + key);
            }
        }
Пример #3
0
 public void Reset()
 {
     innerPQ = copy;
 }