Pagini recente » Cod sursa (job #1843962) | Cod sursa (job #3222513) | Cod sursa (job #2254457) | Cod sursa (job #2927670) | Cod sursa (job #250839)
Cod sursa(job #250839)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 2000000
#define MAX_M 1000
long int n, match[MAX_M];
char a[MAX+2], b[MAX+2];
//read the graph from input file
void read_file()
{
FILE *fin;
if ((fin = fopen("strmatch.in", "r")) == NULL)
{
printf("Eroare \n");
exit(-1);
}
fscanf(fin, "%s", &a[1]);
a[0] = ' ';/*
for (i = 0; i < strlen(ta); i++)
a[i+1] = ta[i];*/
b[0] = ' ';
fscanf(fin, "%s", &b[1]);/*
for (i = 0; i < strlen(tb); i++)
b[i+1] = tb[i];*/
fclose(fin);
//printf("Buzz %s %s\n", a, b);
}
//match the strings
void string_match(char *a, char *b)
{
long int lg_a, lg_b, i, k, q;
long int pi[MAX + 2];
//printf("%s %ld\n%s %ld\n", a, strlen(a), b, strlen(b));
lg_a = strlen(a);
lg_b = strlen(b);
pi[0] = -1;
pi[1] = 0;
k = 0;
for (i = 2; i < lg_a; i++)
{
while (k && a[k+1] != a[i])
k = pi[k];
if (a[k+1] == a[i])
k++;
pi[i] = k;
//printf("k = %ld i %ld pi[%ld] %ld a[%ld]=%c\n", k, i, i, pi[i], i, a[i]);
}
n = -1;
q = 0;
for (i = 1; i < lg_b; i++)
{
while (q && a[q+1] != b[i])
{
q = pi[q];
}
if (a[q+1] == b[i])
{
q++;
}
//printf("q = %ld i %ld b[%ld] %ld a[%ld]=%c\n", q, i, i, b[i], q, a[q + 1]);
if (q == lg_a - 1)
{
n++;
q = pi[q];
//printf("Find one\n");
if (n < MAX_M)
{
match[n] = i - lg_a + 1;
}
}
}
}
void write_file()
{
FILE *fout;
long int i;
fout = fopen("strmatch.out", "w");
n++;
fprintf(fout, "%ld\n", n);
if (n > 1000)
n = 1000;
for (i = 0; i < n; i++)
fprintf(fout,"%ld ", match[i]);
fclose(fout);
}
int main()
{
//read the file
read_file();
//match the strings
string_match(a, b);
//write the output file
write_file();
return 0;
}