1. 程式人生 > >洛谷 P3657 [USACO17FEB]Why Did the Cow Cross the Road II P

洛谷 P3657 [USACO17FEB]Why Did the Cow Cross the Road II P

() 大坑 子序列 ble 序列 min col pan tps

題面

大意:讓你把兩個n的排列做匹配,連線不想交,而且匹配的數字的差<=4,求最大匹配數

sol:(參考了kczno1的題解)對於第一個排列從左往右枚舉,用樹狀數組維護到達另一個序列第i個數字的最大值。

技術分享圖片
#include <cstdio>
#include <algorithm>
using namespace std;
const int N=100005;
int n,a[N],b[N],f[N],t[N];
#define lowbit(x) ((x)&(-x))
inline void ins(int x,int v){for(;x<=n;x+=lowbit(x)){if
(t[x]>v)break;t[x]=v;}} inline int que(int x){int re=0; for(;x;x-=lowbit(x))re=max(re,t[x]);return re;} int main() { int i,j,x; scanf("%d",&n);for(i=1;i<=n;i++)scanf("%d",&a[i]);for(i=1;i<=n;i++)scanf("%d",&x),b[x]=i; for(i=1;i<=n;i++) { for(j=max(1,a[i]-4);j<=min(n,a[i]+4
);j++)f[j]=que(b[j]-1); for(j=max(1,a[i]-4);j<=min(n,a[i]+4);j++)ins(b[j],f[j]+1); }printf("%d\n",que(n)); }
View Code

--------------------分割線-下方無關----------------

大概是受了大佬的啟發,我水掉了一個留了半年多的大坑(最長公共子序列的模板)直接貼鏈接和代碼吧

題面

技術分享圖片
#include <cstdio>
#include <algorithm>
using namespace std;
const int N=100005; int n,a[N],b[N],f[N],t[N]; #define lowbit(x) ((x)&(-x)) inline void ins(int x,int v){for(;x<=n;x+=lowbit(x)){if(t[x]>v)break;t[x]=v;}} inline int que(int x){int re=0; for(;x;x-=lowbit(x))re=max(re,t[x]);return re;} int main() { int i,x; scanf("%d",&n); for(i=1;i<=n;i++)scanf("%d",&a[i]); for(i=1;i<=n;i++)scanf("%d",&x),b[x]=i; for(i=1;i<=n;i++) { f[a[i]]=que(b[a[i]]-1); ins(b[a[i]],f[a[i]]+1); }printf("%d\n",que(n)); }
View Code

洛谷 P3657 [USACO17FEB]Why Did the Cow Cross the Road II P