JZOJ 5441. 【NOIP2017提高A组冲刺11.1】序列
Description
給定一個(gè)1~n的排列x,每次你可以將x1~xi翻轉(zhuǎn)。你需要求出將序列變?yōu)樯虻淖钚〔僮鞔螖?shù)。有多組數(shù)據(jù)。
Input
第一行一個(gè)整數(shù)t表示數(shù)據(jù)組數(shù)。
每組數(shù)據(jù)第一行一個(gè)整數(shù)n,第二行n個(gè)整數(shù)x1~xn。
Output
每組數(shù)據(jù)輸出一行一個(gè)整數(shù)表示答案。
Sample Input
1
8
8 6 1 3 2 4 5 7
Sample Output
7
Data Constraint
對(duì)于100%的測(cè)試數(shù)據(jù),t=5,n<=25。
對(duì)于測(cè)試點(diǎn)1,2,n=5。
對(duì)于測(cè)試點(diǎn)3,4,n=6。
對(duì)于測(cè)試點(diǎn)5,6,n=7。
對(duì)于測(cè)試點(diǎn)7,8,9,n=8。
對(duì)于測(cè)試點(diǎn)10,n=9。
對(duì)于測(cè)試點(diǎn)11,n=10。
對(duì)于測(cè)試點(diǎn)i (12<=i<=25),n=i。
Solution
別被題目嚇到,這題的正解就是迭代加深搜索。
可是怎么剪枝呢(本人搜索能力較差)?
如果相鄰兩個(gè)數(shù)的差大于1(這樣數(shù)對(duì)稱之為逆對(duì))的話,那么顯然至少要一次交換才能換過來(lái),
那么如果當(dāng)前的交換次數(shù)加上逆對(duì)的個(gè)數(shù)大于當(dāng)前迭代的深度,就可以直接退出了。
Code
#include<cstdio> #include<algorithm> using namespace std; int n,ans; bool pd; int a[26]; inline int read() {int X=0,w=1; char ch=0;while(ch<'0' || ch>'9') {if(ch=='-') w=-1;ch=getchar();}while(ch>='0' && ch<='9') X=(X<<3)+(X<<1)+ch-'0',ch=getchar();return X*w; } inline void dfs(int x,int y) {if(x+y>ans) return;bool p=true;for(int i=1;i<=n;i++)if(a[i]!=i){p=false;break;}if(p){pd=true;return;}for(int i=2;i<=n;i++){int z=y;if(i<n){if(abs(a[i]-a[i+1])==1) z++;if(abs(a[1]-a[i+1])==1) z--;}reverse(a+1,a+1+i);dfs(x+1,z);if(pd) return;reverse(a+1,a+1+i);} } int main() {int T=read();while(T--){n=read();int s=pd=0;for(int i=1;i<=n;i++){a[i]=read();if(i>1 && abs(a[i]-a[i-1])>1) s++;}for(ans=0;!pd;ans++) dfs(0,s);printf("%d\n",--ans);}return 0; }總結(jié)
以上是生活随笔為你收集整理的JZOJ 5441. 【NOIP2017提高A组冲刺11.1】序列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JZOJ 5440. 【NOIP2017
- 下一篇: JZOJ 5443. 【NOIP2017