標籤:lis 離散化
【離散化+LIS】swjtuOJ 2091
【註:交大的看到這篇文章要學會自己寫,不要為了比賽而比賽!~】
題目大意
給你兩組n個數的序列,求他們最長公用序列(LCS),n<=10^5
對第一組序列數字編號,再對第二組序列構造他們編號對應的序列s,求解序列s的最長上升子序列即可(LIS)
說一下思路
- 這道題之前沒做過,編號過程有人說是離散化,還不是很清楚,注意{a}序列中的數字可能在{b}序列不存在,要判斷mp[a[i]]是否為空白;LIS用O(NlogN)的演算法,採用二分思想,這裡順便學習下了
?數組a[]使用前要清空
參考代碼
/* 離散化 + LIS *//*Author:Hacker_vision*/#include <iostream>#include <cstdio>#include <algorithm>#include <map>#include <vector>#include <queue>#include <cstring>#include <cmath>#include <climits>#define eps 1e-8#define ll long long#define clr(k,v) memset(k,0,sizeof(k))using namespace std;const int _max = 1e5 + 10;map<int,int>mp;int a[_max],b[_max],c,d,n;//用二分尋找的方法找到一個位置,使得num>b[i-1]且num<b[i],並用num代替b[i]int bsearch(int num,int L,int R){ int mid; while(L <= R){ mid = (L + R) >> 1; if( num >= b[mid]) L = mid + 1; else R = mid - 1; } return L;}int DP(int n){//最長上升子序列,O(NlogN) if(n == 1) return 0;//沒有公用部分 int len = 1,pos; b[1] = a[1]; for(int i = 2; i <= n; ++ i){ if(a[i]>=b[len]){//如果a[i]比b[]數組中最大還大,直接插入到後面即可 len++; b[len] = a[i]; } else{ pos = bsearch(a[i],1,len);//用二分尋找的方式在b[]數組中找出第一個比a[i]大…… b[pos] = a[i]; //的位置並且讓a[i]替代這個位置 } } return len;}int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); #endif // ONLINE_JUDGE while(scanf("%d",&n)==1){ mp.clear(); clr(a,0); // clr(b,0); int top = 1; for(int i = 1; i <= n; ++ i){ scanf("%d",&c); mp[c] = top++;//對序列a中的元素編號 } top = 1; for(int i = 1; i <= n; ++ i){ scanf("%d",&d); if(mp[d]) a[top++] = mp[d];//構造帶LIS的序列a[],注意不一定有n個公用元素 } printf("%d\n",DP(top)); } return 0;}
- 加粗
Ctrl + B
- 斜體
Ctrl + I
- 引用
Ctrl + Q
- 插入連結
Ctrl + L
- 插入代碼
Ctrl + K
- 插入圖片
Ctrl + G
- 提升標題
Ctrl + H
- 有序列表
Ctrl + O
- 無序列表
Ctrl + U
- 橫線
Ctrl + R
- 撤銷
Ctrl + Z
- 重做
Ctrl + Y
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【離散化+LIS】swjtuOJ 2091