跳到正文

题解

题解 P1381 【单词背诵】

kkksc03约 3 分钟
原文
文章信息与版本

文章信息

发布
2013年7月16日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟
获赞
263
题目
P1381

版本

  1. v1当前

这道题如果直接模拟只能够过四个数据,所以我用了二分查找的方法,然后找出相连的包含最多要背的单词并且单词长度最短。(注意,文段中的单词可能是多余的,也就是不用背的。)

代码如下

delphi
var a:array[1..1000] of string[10];
    b:array[1..100000] of string[10];
    len,f:array[0..1000] of longint;
    s:array[0..100000] of longint;
    i,j,m,n,t:longint;
procedure qsort(l,r:longint);
var i,j:longint;
    mid,st:string[10];
begin
  i:=l;j:=r;
  mid:=a[(l+j) div 2];
  while i<=j do
   begin
     while a[i]<mid do inc(i);
     while a[j]>mid do dec(j);
     if i<=j then
      begin
        st:=a[i];a[i]:=a[j];a[j]:=st;
        inc(i);dec(j);
      end;
   end;
  if l<j then qsort(l,j);
  if i<r then qsort(i,r);
end;
procedure half(st:string[10];l,r:longint);
var mid:longint;
begin
  if l+1<r then
   begin
     mid:=(l+r) div 2;
     if a[mid]<=st then half(st,mid,r) else half(st,l,mid);
   end
  else
   begin
     if a[l]<>st then exit;
     if f[l]=0 then inc(t);
     inc(f[l]);
     s[i]:=l;
   end
end;

begin
  readln(n);
  for i:=1 to n do readln(a[i]);
  qsort(1,n);
  readln(m);
  for i:=1 to m do readln(b[i]);
  for i:=1 to n do len[i]:=maxint;
  i:=0;
  while i<m do
   begin
     inc(i);
     half(b[i],1,n+1);
     while (j<i)and((f[s[j]]>1)or(s[j]=0)) do
      begin
        if s[j]<>0 then dec(f[s[j]]);
        inc(j);
      end;
     if i-j+1<len[t] then len[t]:=i-j+1;
   end;
  writeln(t);
  writeln(len[t]);
end.