數據結構實驗之棧六:下一較大值(二) Time Limit: 150MS Memory Limit: 8000KB Submit Statistic PRoblem Description
對于包含n(1<=n<=100000)個整數的序列,對于序列中的每一元素,在序列中查找其位置之后第一個大于它的值,如果找到,輸出所找到的值,否則,輸出-1。
Input
輸入有多組,第一行輸入t(1<=t<=10),表示輸入的組數; 以后是 t 組輸入:每組先輸入n,表示本組序列的元素個數,之后依次輸入本組的n個元素。
Output
輸出有多組,每組之間輸出一個空行(最后一組之后沒有); 每組輸出按照本序列元素的順序,依次逐行輸出當前元素及其查找結果,兩者之間以–>間隔。
Example Input
2
4 12 20 15 18
5 20 15 25 30 6
Example Output
12–>20 20–>-1 15–>18 18–>-1
20–>25 15–>25 25–>30 30–>-1 6–>-1
Hint
本題數據量大、限時要求高,須借助棧來完成。
。。。。。。這題看了好久 難道真的就是條咸魚?
#include <bits/stdc++.h>#include <cstdio>#include <stack>#define N 100100using namespace std;struct node{ int num,id,next;//id確定位置,所求值存入next}a[N];int main(){ int t; scanf("%d",&t); stack<struct node>p; for(int i =1;i<=t;i++) { while(!p.empty()) { p.pop(); }//若棧不空,清棧; int n; if(i>1) printf("/n"); scanf("%d",&n); for(int j=1;j<=n;j++) { scanf("%d",&a[j].num); a[j].id=j; a[j].next=-1; if(p.empty()) { p.push(a[j]); } else { while(!p.empty())//棧不空時,取出棧頂元素與當前元素比較 { struct node b; b=p.top(); if(b.num<a[j].num)//若當前元素大于棧頂元素, { a[b.id].next=a[j].num;//棧頂元素的next即為當前元素 p.pop();//刪除棧頂元素 } else break; } p.push(a[j]);進棧 } } for(int j=1;j<=n;j++) { printf("%d-->%d/n",a[j].num,a[j].next); } }}
|
新聞熱點
疑難解答