您的位置:首页 > 其它

UVA - 10635 Prince and Princess (求LIS)

2017-11-17 11:16 351 查看
The Prince moves along the sequence: 1 –> 7 –> 5 –> 4 –> 8 –> 3 –> 9 (Black arrows), while thePrincess moves along this sequence: 1 –> 4 –> 3 –> 5 > 6 –> 2 –> 8 –> 9 (White arrow).The King – their father, has just come. “Why move separately? You are brother
and sister!” saidthe King, “Ignore some jumps and make sure that you’re always together.”For example, if the Prince ignores his 2nd, 3rd, 6th jump, he’ll follow the route: 1 –> 4 –> 8 –>9. If the Princess ignores her 3rd, 4th, 5th, 6th jump, she’ll follow
the same route: 1 –> 4 –> 8 –>9, (The common route is shown in figure 3) thus satisfies the King, shown above. The King wants toknow the longest route they can move together, could you tell him?

题意:求最长公共子序列,因为元素是不重复的,所以只需要找出第2条序列中的元素,在第1条中的位置,没有的用0代替, 接下去就是求最长上升子序列了。我用了map记录第一条中的元素位置,实际上是不用这么做, 开个数组记录就可以了。

ps:dp求最长子序列会超时, 要用nlogn的算法。

#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int mx = 255;
map<int, int> mp;
int n, p, q, num[mx * mx], inc[mx * mx];
int main()
{
int t, a, b;
scanf("%d", &t);
for(int i = 1; i <= t; i++){    //一直用i 容易出错, 变量名最好复杂
mp.clear();
scanf("%d%d%d", &n, &p, &q);
p++; q++;
for(int k = 1; k <= p; k++){
scanf("%d",&a);
mp[a] = k;
}

for(int k = 1; k <= q; k++){
scanf("%d", &b);
num[k] = mp[b];
}
memset(inc, 0, sizeof(inc));
int cor, len = 1;

inc[0]  = num[1];
for(int k = 2; k <= q; k++){

cor = upper_bound(inc, inc + len, num[k]) - inc;
if(cor == len){
inc[len] = num[k];
len++;
continue;
}

inc[cor] = num[k];
}

printf("Case %d: %d\n",i, len);

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: