- #include <iostream>
- #include <iterator>
- #include <time.h>
- #include <vector>
- using namespace std;
- #define MAXNUM 10
- int MaxLPre[MAXNUM];
- void CreateRAdjTable(vector<int> &list,vector<int> *RAdjTable) //创建反邻接表;
- {
- int size=list.size();
- for(int i=0;i<size-1;i++)
- for(int j=i+1;j<size;j++)
- {
- if(list[i]<list[j]) RAdjTable[j].push_back(i);
- }
- }
- int MaxL(const vector<int> &list,vector<int> *RAdjTable,int *L,int j) //寻找边i->j中,L[i]最大者;
- {
- int maxl=0;
- for(int i=0;i<RAdjTable[j].size();i++)
- {
- if(L[ RAdjTable[j][i] ]>maxl)
- {
- maxl=L[ RAdjTable[j][i] ];
- MaxLPre[j]=RAdjTable[j][i]; //找到后,标志J的前驱RAdjTable[j][i];
- }
- }
- return maxl;
- }
- void CreateLS(const vector<int> &list,vector<int> *RAdjTable,int *L)
- {
- for(int j=0;j<MAXNUM;j++)
- if( RAdjTable[j].empty() )
- {
- L[j]=1; //对没有入边的结点,令其L=1;
- MaxLPre[j]=-1; //令其前驱等于-1;
- }
- else
- {
- L[j]=1+MaxL(list,RAdjTable,L,j);
- }
- }
- void ShowPath(const vector<int> &list,int j)
- {
- vector<int> stack;
- while(j != -1)
- {
- stack.push_back(list[j]);
- j=MaxLPre[j];
- }
- while(!stack.empty())
- {
- cout<<stack.back()<<"\t";
- stack.pop_back();
- }
- cout<<endl;
- }
- void main()
- {
- vector<int> list;
- vector<int> RAdjTable[MAXNUM];
- int L[MAXNUM];
- srand(time(0));
- while(list.size() != MAXNUM)
- {
- list.push_back(rand()%100);
- }
- copy(list.begin(),list.end(),ostream_iterator<int>(cout,"\t"));
- cout<<endl;
- CreateRAdjTable(list,RAdjTable);
- CreateLS(list,RAdjTable,L);
- for(int i=0;i<MAXNUM;i++)
- cout<<L[i]<<"\t";
- cout<<endl;
- cout<<"最长递增子序列:"<<endl;
- int j=0;
- for(int i=0;i<MAXNUM;i++)
- if(L[i]>L[j]) j=i;
- ShowPath(list,j);
- }
第7周作业3——最长递增子序列
最新推荐文章于 2024-08-28 12:30:52 发布