[Algorithm] PROBLEM GetString
Given a string S of length not exceeding 10 ^ 5, and set A with n elements(n≤100) consisting of ASCII characters, are case sensitive. Look for consecutive substring in S that contain the complete set of characters in A and the shortest length.
(Consecutive substring is the string with the characters in the order of A and can be far apart)
Data on: file GETSTRING.INP
The first line contains contains a string S
The first line 2 the number n.
The next N lines, each containing 1 A character in the set.
Data out: file GETSTRING.OUT
Including 1 single line recorded the shortest length find substring.
Example:
GETSTRING.INP
hello the gioin
4
t
and
g
the
GETSTRING.OUT
7
———————
call F[in][j] is the distance from the characters A[in] (The[in] = s[j]) to A[i-1] in string S.
I need to find the string length is the shortest distance from A[n] to A[1].
F[in][j] is calculated as follows:
Browse array A, with each element of the array A string s approval if A[in] = s[j] then we perform:
if the A[0] then f[in][j] = 1;
reverse f[in][j] = j-start + temp;
in which the start is located near the most j f[i-1][start] > 0 and temp is the value f[i-1][start] (length from S[start] to S[x] that S[x] =A[1])
Finally KQ is of f min[A-1][j] (j=0 -> ns, with min > 0, if no values >0 then min = 0)
The test results and F[in][j] on ideone.com
#include<cstdio>
#include<cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
getline(cin,s);
int n;
scanf("%d",&n);
char A[n];
int f[n][s.length()];
for (int i=0; i<n; i++)
{
scanf("%c",&A[i]);
scanf("%c",&A[i]);
//printf("%c ",A[i]);
}
//cout<<endl<<s<<endl;
//printf("%dn",n);
for (int i=0; i<n; i++)
for (int j=0; j<s.length(); j++)
f[i][j] = 0;
int begin = 0, min = 0;
for (int i=0; i<n; i++)
{
int temp = 0, check = 0, start = 0;
//temp la gia tri do dai tai no, check: neu co 1 lan bang roi, start noi bat dau xet
for (int j=begin; j<s.length(); j++)
{
if (i>0 && f[i-1][j] > 0) { start = j; temp = f[i-1][j]; } // tim start va temp
if (A[i] == s[j])
{
//printf("%3c%3d%3dn",A[i],i,j);
if (check == 0) begin = j; // chua co ky tu nao bang thi j la noi bat dau
if (i==0) f[i][j] = 1; // xet cho A[0]
else
{
f[i][j] = j-start + temp; //vi tri hien tai - noi bat dau + gia tri do dai
}
check = 1;
if (i==n-1)
{
if (f[i][j] < min || min == 0) min = f[i][j];
}
}
}
}
for (int i=0; i<n; i++)
{
for (int j=0; j<s.length(); j++)
printf("%4d",f[i][j]);
printf("n");
}
printf("%d",min);
return 0;
}

One other solutions refer here



Recent Comments