标签:style http color os strong 数据
题目链接:Click Here~
题目描述:
给你n个数,要你得到的最后结果是从下到大排序。但是给出的序列不一定是有序你,要通过你的调整。问:要经过哪几个位置上的数的调整?
算法分析:
一开始,我的思路是直接模拟一边消除逆序数就可以了,因为我看数据很小,只有30.但是提交之后却TEL了。后来上网查了一下,看到有一个人的思路还是很好的。就是说运用到了动态规划的思想。确实很巧妙啊!
思路:在查询到当前第i个数的时候,你必须保证其后面的数是有序的,且都比i大。只要保证了这一个条件之后,我们可以从快排的思想得知这是正确的。但是如何可以实现呢?其实也很简单。比如,但前你查询到了第i个了,可是第i个不满足条件,而且这是后又有两种情况。(第i个数本应该的数在哪里?)1、可能就在最前面,那个此时你可以直接Flip操作就可以了。2、不再最前面,此时你可以先找到最大数的位置,然后先将最大数Flip操作实现其到最前面,然后再实现操作1就OK了。
例:
2 4 1 3 5
此时我们查询到了3这个位置,你会发现3这个位置本来应该是4的但是现在不是,所以你要进行Flip操作。但是你有发现4不再最前面,即使你实现了Flip操作也得不到正确结果。所以,你要先把4Flip到最前面,即2的位置。
4 2 1 3 5
之后在Flip得到
3 1 2 4 5
。。。。。。这样一直查询下去,O(n)的算法复杂度实现就可以了。
#include <iostream> #include <algorithm> #include <string> #include <iterator> #include <sstream> #include <deque> #include <vector> #include <cstdio> using namespace std; int main() { string line; while(getline(cin,line)) { int x; deque<int> deq; deque<int>::iterator iter; istringstream ss(line); while(ss>>x){ deq.push_front(x); cout<<x<<" "; } cout<<endl; for(iter = deq.begin();iter != deq.end();++iter){ deque<int>::iterator iMax = max_element(iter,deq.end()); if(iter != iMax){ //当前这个数的位置不应该待在这 if(iMax != deq.end()-1){ //最大数不再最前面(操作1) reverse(iMax,deq.end()); cout<<distance(deq.begin(),iMax)+1<<' '; } reverse(iter,deq.end()); //操作2 cout<<distance(deq.begin(),iter)+1<<' '; } } cout<<"0"<<endl; } return 0; }
uva Stacks of Flapjacks,布布扣,bubuko.com
标签:style http color os strong 数据
原文地址:http://blog.csdn.net/zhongshijunacm/article/details/38033205