USACO Longest Prefix

本文讨论了如何通过暴力动态规划方法解决给定字符串的最长前缀表示问题,涉及字符预处理与字符串匹配算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:给出一个长字符串,问最长的前缀,使得这个前缀能用给出的一些元素组合而成

思路:暴力dp,dp[i]表示长度为i的前缀能否被表示

 

 1 /*{
 2 ID:a4298442
 3 PROB:prefix
 4 LANG:C++
 5 }
 6 */
 7 #include<iostream>
 8 #include<fstream>
 9 #include<cstring>
10 #include<algorithm>
11 #define maxn 109
12 using namespace std;
13 ifstream fin("prefix.in");
14 ofstream fout("prefix.out");
15 //#define fin cin
16 //#define fout cout
17 int dp[200009];
18 char premitive[maxn*3][maxn],ch[200009];
19 int check(int x,int y,int totle)
20 {
21     char temp[maxn],h=0;
22     for(int i=x;i<=y;i++)
23     {
24         temp[++h]=ch[i];
25     }
26     temp[h+1]='\0';
27     for(int i=1;i<=totle;i++)
28     {
29         if(strcmp(temp+1,premitive[i]+1)==0)return 1;
30     }
31     return 0;
32 }
33 int main()
34 {
35     int n,h=0;
36     while(1)
37     {
38         fin>>(premitive[++h]+1);
39         if(premitive[h][1]=='.'){h--;break;}
40     }
41     char c;
42     int len=0;
43     while(fin>>c)
44     {
45         if('A'<=c && c<='Z')ch[++len]=c;
46     }
47     ch[len+1]='\0';
48     dp[0]=1;
49     for(int i=1;i<=len;i++)
50     {
51         for(int j=max(i-10,1);j<=i;j++)
52         {
53             if(check(j,i,h)&& dp[j-1])
54             {
55                 dp[i]=1;break;
56             }
57         }
58     }
59     int ans=0;
60     for(int i=len;i>=1;i--)
61     {
62         if(dp[i]==1)
63         {
64             ans=i;
65             break;
66         }
67     }
68     fout<<ans<<endl;
69     return 0;
70 }

 

转载于:https://www.cnblogs.com/philippica/p/4321933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值