Removing the largest values encountered so far in a list
You are using a C++ compiler!

So you should also use its features:


don't declare all variables up front but as late as possible
don't using namespace std; that only gives you trouble later on
you don't need to return 0; at the end of main


Formatting

Your formatting can be improved. You should use more spaces especially around (binary) operators, this makes it easier to parse (or rather tokenize) the code with your eye.

Naming

You have nearly only single letter names which is bad. The fact that two of them look like macro names does not make it better. Consider:


N -> populationHeadCount
M -> executionCount
val -> currentVisitorWealth
visits -> stillLivingWealthiest


Unused variable

The variable i is initialized and incremented but never read.

Inserting "the king"

Your code unconditionally inserts the wealth val even if it is the king (-1), thus introducing even more entries in visits.

Speed up

Reading rules more closely than you have given them here yields:


  You may assume that no two citizens have the same wealth. 


Which makes this problem a perfect fit for an std::set (as mentioned by Loki):

#include &lt;iostream&gt;
#include &lt;set&gt;
#include &lt;algorithm&gt;

int main() {
  int populationHeadCount, expectedExecutionCount;
  std::cin &gt;&gt; populationHeadCount &gt;&gt; expectedExecutionCount;
  std::set&lt;int&gt; stillLivingWealthiest;
  int executionNumber = 0;
  while (executionNumber &lt; expectedExecutionCount) {
    int currentVisitorWealth;
    std::cin &gt;&gt; currentVisitorWealth;
    if (currentVisitorWealth == -1) {
      std::cout &lt;&lt; *--stillLivingWealthiest.end() &lt;&lt; std::endl;
      stillLivingWealthiest.erase(--stillLivingWealthiest.end());
      ++executionNumber;
    } else {
      stillLivingWealthiest.insert(currentVisitorWealth);
    }
  }
}


Explanation: A std::set stores the elements sorted from minimum to maximum, so we only need to look at the end to get and delete the maximal element.