部落卫队问题(深度优先搜索)

来源:互联网 发布:java如何停止一个线程 编辑:程序博客网 时间:2024/04/27 20:22

Description

原始部落byteland中的居民们为了争夺有限的资源,经常发生冲突。几乎每个居民都有他的仇敌。部落酋长为了组织一支保卫部落的队伍,希望从部落的居民中选出最多的居民入伍,并保证队伍中任何2个人都不是仇敌。 

.编程任务: 

给定byteland部落中居民间的仇敌关系,编程计算组成部落卫队的最佳方案。 

Input

第1行有2个正整数n(n<=100)和m,表示byteland部落中有n位居民,居民间有m个仇敌关系。居民编号为1,2,…,n。接下来的m行中,每行有2个正整数u和v,表示居民u与居民v是仇敌。

Output

第1行是部落卫队的顶人数; 
第2行是卫队组成xi ,1 ≤ i ≤ n ,xi=0 表示居民i不在卫队中,xi =1表示居民i在卫队中。

Sample Input

 

7    10       3    1    2        1    0    1    0    0    0    1    1    4    2    4    2    3    2    5    2    6    3    5    3    6    4    5    5    6   

 

Sample Output

 

3    1    0    1    0    0    0    1

解题思路:用多个数组储存仇敌关系、选择方案,并且用搜索,如果现在的人数大于最大的人数就更新最大人数,然后循环,如果该人不在卫队里就把它放进去,继续搜索,最后输出总数,并且输出01 

代码:
type
  ss=set of 1..100;
var
  a:array[1..1000] of integer;
  s,c:array[1..1000] of boolean;
  b:array[1..1000] of ss;
  i,j,k,n,max,ren,x,y:integer;
  sss:ss;

procedure dfs(now,t:integer;sss:ss);
  var
    i:integer;
  begin
    if now>max then begin max:=now; s:=c; end;
    for i:=t+1 to n do
      if not(i in sss) then
        begin
          c[i]:=true;
          dfs(now+1,i,sss+b[i]);
          c[i]:=false;
        end;
end;

begin
  fillchar(c,sizeof(c),false);
  sss:=[];
  readln(n,k);
  ren:=0;  max:=0;
  for i:=1 to k do
    begin
      readln(x,y);
      b[x]:=b[x]+[y];
    end;
  sss:=[];
  dfs(0,0,sss);
  writeln(max);
  for i:=1 to n do
    if s[i] then write(1,' ')
      else write(0,' ');
end.
0 0
原创粉丝点击