Saturday, October 29, 2011

Flood Fill

//http://www.mitbbs.com/article_t1/JobHunting/31909771_0_5.html
//白话文应该是: 下坡时把数进堆栈 (这样堆栈中最上元素是最小的,保存一个下坡序
//列),上坡时:如果
//有底的话(堆栈中至少有两个元素),找出底,flood(累加,顶减底乘长度)。
//知道过完为止。
int water(int * a, int n){
  stack > mystack;
  int water = 0;
  for(int i = 0; i    while(!mystack.empty() && mystack.top().second <= a[i]){ //上坡
      int bottom = mystack.top().second; //底
      mystack.pop();
      if( mystack.empty())  //堆栈中只有一个元素,不能形成底。
        break;
      int top = mystack.top().second < a[i]?  mystack.top().second:  a[i];  //找到顶(次大数)

      int length = i - mystack.top().first - 1;  //长度
      water = water + (top-bottom)* length;  //填充
    }  //当前上坡处理完。
    mystack.push(make_pair(i, a[i]));  //下坡,进堆栈。

    //上坡无底的话,是什么都不做的,因为上次进堆栈的元素直接出堆栈了,只是查了一下底(至少两元素在堆栈)。
  }
  return water;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int value[10] = {5,5,1,7,1,1,5,2,7,6};


    int result=0;

    cout << result;

    result = water(value, 10);
    cout << result;

    return 0;
}

No comments: