Ⅰ 璁炬爤鐨勫瓨鍌ㄧ┖闂翠負S錛1錛歮錛夛紝鍒濆嬬姸鎬佷負TOP錛漨+1銆傜粡榪囦竴緋誨垪鍏ユ爤涓庨鏍堟搷浣滃悗錛孴OP錛漨
m+1 銆
榪欎釜鏍堟槸浠庢爤欏跺悜鏍堝簳鍘嬬殑錛屼竴鑸騫蟲椂鏄浠庢爤搴曞悜鏍堥《鍘嬶紝榪欓亾棰樼洰涓鏄鍊掕繃鏉ョ殑銆
鑻TOP鈮n鏃訛紝鍒欑粰鍑烘孩鍑轟俊鎮錛屼綔鍑洪敊澶勭悊錛堣繘鏍堝墠棣栧厛媯鏌ユ爤鏄鍚﹀凡婊★紝婊″垯婧㈠嚭錛夛紱緗甌OP=TOP+1錛堟爤鎸囬拡鍔1錛屾寚鍚戣繘鏍堝湴鍧錛夛紱S(TOP)=X錛岀粨鏉燂紙X涓烘柊榪涙爤鐨勫厓緔狅級銆
鎵╁睍璧勬枡錛
鑻TOP鈮0錛屽垯緇欏嚭涓嬫孩淇℃伅錛屼綔鍑洪敊澶勭悊(閫鏍堝墠鍏堟鏌ユ槸鍚﹀凡涓虹┖鏍堬紝 絀哄垯涓嬫孩)錛沊=S(TOP)錛岋紙閫鏍堝悗鐨勫厓緔犺祴緇橷錛夛細TOP=TOP-1錛岀粨鏉燂紙鏍堟寚閽堝噺1錛屾寚鍚戞爤欏訛級銆
瀹氫箟stack鐨勭畝鍗曚唬鐮侊細
stack<int> sta;
鍏ユ爤錛歴ta.push(x);
鍑烘爤錛歴ta.pop();
鍒ゆ柇鏍堢殑澶у皬錛 sta.size();
鍒ゆ柇鏍堟槸鍚︿負絀猴細sta.empty();