做这道题学会了三点:1,二分图的两个顶点,一定是分属两个不同的集合,一开始建图的时候,直接把可能有恋爱关系的人相连,这样其实就不是二分图,正确的应该是把可能有恋爱关系的男女相连。2,提交错误后,比如WA和RE,一定要跟踪变量运行,而不要只看程序。3,多组数据的时候,各变量和数组记得赋初值

好久没做二分图的题了,其实这题真的很水,但弄了半天,TAT...

照以上方法建图后,其实就是求二分图的最大独立集,最大独立集=总顶点数-最大匹配

program poj2771;
type
  node=record
    x,y,next:longint;
  end;
  node1=record
    h:integer;
    fm,fs:string;
  end;
  arr=array[1..500] of node1;
var
  tot:longint;
  flag:boolean;
  n,m,k,i,ans,lx,ly:integer;
  x,y:arr;
  g:array[1..250000] of node;
  used:array[1..500] of boolean;
  link,first:array[1..500] of integer;
procedure work(var a:arr;var l:integer;s:string);
var
  p,code:integer;
begin
  inc(l);
  p:=pos(' ',s);
  val(copy(s,1,p-1),a[l].h,code);
  delete(s,1,p+2);
  p:=pos(' ',s);
  a[l].fm:=copy(s,1,p-1);
  a[l].fs:=copy(s,p+1,length(s)-p);
end;
procedure init;
var
  i,j,p:integer;
  s:string;
begin
  readln(n);
  for i:=1 to n do
    first[i]:=-1;
  for i:=1 to n do
  begin
    readln(s);
    p:=pos(' ',s);
    if s[p+1]='M' then work(y,ly,s)
      else work(x,lx,s);
  end;
  for i:=1 to lx do
    for j:=1 to ly do
      if (abs(x[i].h-y[j].h)<=40) and (x[i].fm=y[j].fm) and (x[i].fs<>y[j].fs) then
      begin
        inc(tot);
        g[tot].x:=i;
        g[tot].y:=j;
        g[tot].next:=first[i];
        first[i]:=tot;
      end;
end;
function find(s:integer):boolean;
var
  temp:integer;
begin
  temp:=first[s];
  find:=true;
  while temp<>-1 do
  begin
    if used[g[temp].y] then
    begin
      used[g[temp].y]:=false;
      if (link[g[temp].y]=0) or find(link[g[temp].y]) then
      begin
        link[g[temp].y]:=s;
        exit;
      end;
    end;
    temp:=g[temp].next;
  end;
  find:=false;
end;
begin
  readln(m);
  for k:=1 to m do
  begin
    fillchar(g,sizeof(g),0);
    fillchar(link,sizeof(link),0);
    fillchar(first,sizeof(first),0);
    lx:=0;
    ly:=0;
    tot:=0;//小心,不赋初值会RE
    init;
    for i:=1 to n do
    begin
      fillchar(used,sizeof(used),true);
      flag:=find(i);
    end;
    ans:=0;
    for i:=1 to n do
      if link[i]<>0 then inc(ans);
    writeln(n-ans);
  end;
end.