1045 Favorite Color Stripe (30 分)
Eva is trying to make her own color stripe out of a given one. She would like to keep only her favorite colors in her favorite order by cutting off those unwanted pieces and sewing the remaining parts together to form her favorite color stripe.
It is said that a normal human eye can distinguish about less than 200 different colors, so Eva’s favorite colors are limited. However the original stripe could be very long, and Eva would like to have the remaining favorite stripe with the maximum length. So she needs your help to find her the best result.
Note that the solution might not be unique, but you only have to tell her the maximum length. For example, given a stripe of colors {2 2 4 1 5 5 6 3 1 1 5 6}. If Eva’s favorite colors are given in her favorite order as {2 3 1 5 6}, then she has 4 possible best solutions {2 2 1 1 1 5 6}, {2 2 1 5 5 5 6}, {2 2 1 5 5 6 6}, and {2 2 3 1 1 5 6}.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤200) which is the total number of colors involved (and hence the colors are numbered from 1 to N). Then the next line starts with a positive integer M (≤200) followed by M Eva’s favorite color numbers given in her favorite order. Finally the third line starts with a positive integer L (≤10410^4104) which is the length of the given stripe, followed by L colors on the stripe. All the numbers in a line a separated by a space.
Output Specification:
For each test case, simply print in a line the maximum length of Eva’s favorite stripe.
Sample Input:
6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6
Sample Output:
7
直接看代码注释吧,这种dfs的还真不太好解释。。
30分代码
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
const int maxn = 1e4+10;
int favo[205];
int color[205];
int n,nfavo,ncolor,t;
vector<int> stripe;
map<P,int> mp;
int findStripe(int pos,int index)
{
// 从pos开始,搜索color[index]
// 返回从pos开始,颜色从color[index]开始的最长的favorite color stripe的长度
if(index == nfavo)
return 0;
if(mp.count(make_pair(pos,index)) != 0) //记忆化搜索
return mp[make_pair(pos,index)];
int max_value = 0,temp = 0;
for(int i = pos;i < stripe.size(); i++)
{
if(stripe[i] == color[index])
{
temp++;
max_value = max(max_value,temp+findStripe(i,index+1));
}
}
if(temp == 0) // 没有找到color[index]这种颜色
return findStripe(pos,index+1);
else
return mp[make_pair(pos,index)] = max_value;
}
int main(int argc, char const *argv[])
{
cin >> n;
cin >> nfavo;
memset(favo,0,sizeof(favo));
for(int i = 0;i < nfavo; i++)
{
scanf("%d",&t);
color[i] = t;
favo[t] = 1;
}
cin >> ncolor;
for(int i = 0;i < ncolor; i++)
{
scanf("%d",&t);
if(favo[t] == 1)
stripe.push_back(t);
}
int longest = 0;
if(stripe.size() == 0)
cout << 0 << endl;
else
{
for(int i = 0;i < nfavo; i++) // 每一种颜色作为开头都要搜索
longest = max(longest,findStripe(0,i));
}
cout << longest << endl;
return 0;
}
在这款编程挑战中,Eva的目标是从给定的颜色条纹中裁剪并重组,仅保留她最喜欢的颜色,形成最长的连续颜色条纹。通过深度优先搜索算法,程序帮助Eva找到最优解,实现其个性化颜色条纹的创造。
6万+

被折叠的 条评论
为什么被折叠?



