码迷,mamicode.com
首页 > 其他好文 > 详细

初学并查集-4:6个朋友

时间:2015-01-13 19:15:06      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

题目描述 Description

有这么一种说法:认识6个人,你就认识全世界的人。

Aiden现在有一张关系图,上面记载了N个人之间相互认识的情况。Aiden想知道,他能否只认识6个人就能间接认识这N个人呢?

输入描述 Input Description

第一行,两个数N,M,表示有N个人,M对认识关系。

接下来的M行,每行两个数ai,bi,表示ai与bi相互认识。

不保证认识关系不出现重复,保证ai≠bi。

N个人的编号为1...N。

输出描述 Output Description

若只认识6个人就能间接认识这N个人,则输出“^_^”。

若不行,则第一行输出“T_T”,第二行输出认识6个人最多能间接认识的人的个数。

输出不包括引号。

样例输入 Sample Input

6 7

1 2

1 3

2 4

3 5

4 6

5 6

3 2

样例输出 Sample Output

^_^

数据范围及提示 Data Size & Hint

对于30%的数据,保证0<n≤1000。

对于50%的数据,保证0<n≤5000。

对于100%的数据,保证0<n≤10000,m≤10*n。

type r=record
       num,v:longint;
       end;

var i,j,k,l:longint;
    father:array[1..10000]of longint;
    n,m:longint;
    x,y:longint;
    cost:array[1..10000]of r;
    num:array[1..10000]of integer;
    used:array[1..10000]of boolean;

function find(x:longint):longint;
         begin if father[x]=x
                  then exit(x);
               father[x]:=find(father[x]);
               exit(father[x]);
         end;

procedure union(x,y:longint);
          begin father[find(x)]:=find(father[y]);
          end;

procedure choose;
          var i,j,k:longint;
              max,maxx:longint;
          begin for i:=1 to 6 do
                    begin max:=0;
                          for j:=1 to n do
                              if (cost[j].num>max)and(not used[j])
                                 then begin max:=cost[j].num;
                                            maxx:=j;
                                      end;
                          used[maxx]:=true;
                          l:=l+max;
                    end;
          end;

begin readln(n,m);
      fillchar(father,sizeof(father),0);
      for i:=1 to n do
          father[i]:=i;
      for i:=1 to m do
          begin readln(x,y);
                if find(x)<>find(y)
                   then union(x,y);
          end;
      fillchar(cost,sizeof(cost),0);
      fillchar(num,sizeof(num),0);
      fillchar(used,sizeof(used),false);
      for i:=1 to n do
          inc(num[find(i)]);
      k:=0;
      for i:=1 to n do
          if num[i]<>0
             then begin inc(k);
                        cost[k].v:=i;
                        cost[k].num:=num[i];
                  end;
      l:=0;
      if k<=6
         then begin writeln(‘^_^‘);
                    halt;
              end
         else begin choose;
                    writeln(‘T_T‘);
                    writeln(l);
              end;
end.

初学并查集-4:6个朋友

标签:

原文地址:http://www.cnblogs.com/spiderKK/p/4221920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!