google codejam 2009 Qualification Round Problem C code

本文介绍了一个使用 C++ 实现的字符串匹配算法,该算法能够高效地计算一个给定字符串中与目标模式相匹配的所有子串的数量。通过递归方式更新计数数组,实现了对任意长度输入的有效处理。

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


#include <iostream>
#include <vector>
#include <string>

using namespace std;

const string b("welcome to code jam");
//const string b("a");
const int MAXLEN = 501;
const int m = b.length();
int n;
string a;
int cnt[MAXLEN][20];

void InitArray()
{
 for (int i=0; i<n; ++i)
  for (int j=0; j<m; ++j)
   cnt[i][j] = -1;
 for (int i=0; i<=n; ++i)
  cnt[i][m] = 1;
 for (int i=0; i<m; ++i)
  cnt[n][i] = 0;
}

int Count( int i, int j )
{
 if ( cnt[i][j] > -1 ) return cnt[i][j];
 //if ( i == n ) return cnt[i][j] = 0;

 if ( a[i] == b[j] ) { return cnt[i][j] = (Count( i + 1, j + 1 ) + Count( i + 1, j )) % 10000; }
 else return  cnt[i][j] = Count(i+1, j);
}

int main()
{
#ifndef ONLINE_JUDGE
 freopen("data.txt", "r", stdin);
 freopen("out.txt", "w", stdout);
#endif
 int N;
 
 cin >> N;
 cin.get();
 for (int i=1; i<=N; ++i)
 {
  char astr[MAXLEN];
  cin.getline(astr, MAXLEN);
  a = astr;
        n = a.length();  
  InitArray();
  cout << "Case #"<<i << ": " ;
  int number = Count(0, 0);
  if (number < 1000) cout << 0;
  if (number < 100) cout << 0;
  if (number < 10) cout << 0;
  cout << number;
  cout << "/n";
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值