POJ 2823 單調隊列

來源:互聯網
上載者:User

KD的單調隊列啊!! 十分坑啊~~ 整個下午都浪費在這個上面了~雖然最佳化到了5400ms+了,但是離那些500ms+的神犇們差距太遠了... 應該是有很好的演算法吧,只能一個人想了。

使用單調隊列... 無限TLE啊... 沒看代碼只是自己YY了一遍大概怎麼弄。我理解的的單調隊列大概是這個樣子。

拿範例來說事吧。覺得類似於網路通訊協定中的視窗協議。

8 31 3 -1 -3 5 3 6 7

視窗大小為3

每次更新單調隊列

1.{ 1 };

2.{ 1,3 };

3.{ -1 };  輸出-1

4.{ -3 };輸出-3

5.{ -3,5 };輸出-3

6.{ -3,3 };輸出-3

7.{ 3 }->{ 3,6 };輸出3

8.{ 3,6,7 };輸出3

同樣地對於max序列。

可見規律為:每次輸出隊頭元素,當前元素從隊尾走向隊頭,插入第一個合格地方。保證隊列單調,而且相同的元素儘可能的大,這樣每次維持一個隊列。輸出最前段的元素。但是判斷插入的時候不能從前面向後掃描,這樣時間開銷太大了我就果斷的TLE了一下午,查不出錯誤,後來就隊尾向前掃一遍,找到節點插入就行了。

KD的單調隊列啊~~


#include<iostream>#define MAXN 1000005using namespace std;int date[MAXN];int temp[MAXN];int main(){    int n,c;    int foot=1;    int index=1;    int i,pre;               while( scanf( "%d %d",&n,&c )!=EOF )    {           memset( date,0,sizeof(date) );           memset( temp,0,sizeof(temp) );           for( i=1;i<=n;i++ )                scanf( "%d",&date[i] );           //memset( temp,0,sizeof(temp) );           temp[1]=1;           foot=2;index=1;           for( i=1;i<=n;i++ )           {                if( i-temp[index]+1>c )                    index++;                pre=foot;                while(1)                {                        if( date[i]<=date[temp[pre-1]]&& pre-1>=index )                            pre--;                        else                            break;                }                foot=pre+1;                temp[pre]=i;                if( i==c )                    printf( "%d",date[temp[index]] );                if( i>c )                    printf( " %d",date[temp[index]] );           }           printf( "\n" );           foot=2;index=1;           temp[1]=1;           for( i=1;i<=n;i++ )           {                if( i-temp[index]+1>c )                    index++;                pre=foot;                while(1)                {                        if( date[i]>=date[temp[pre-1]]&&pre-1>=index )                            pre--;                        else                            break;                }                foot=pre+1;                temp[pre]=i;                if( i==c )                    printf( "%d",date[temp[index]] );                  if( i>c )                    printf( " %d",date[temp[index]] );           }           printf( "\n" );    }    return 0;}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.