ACM: 深搜 poj 2531  (一开始,居然…

来源:互联网 发布:淘宝网店加盟哪家好 编辑:程序博客网 时间:2024/06/05 18:54

                                                                     Network Saboteur

Description

A university network is composed of N computers. Systemadministrators gathered information on the traffic between nodes,and carefully divided the network into two subnetworks in order tominimize traffic between parts.
A disgruntled computer science student Vasya, after being expelledfrom the university, decided to have his revenge. He hacked intothe university network and decided to reassign computers tomaximize the traffic between two subnetworks.
Unfortunately, he found that calculating such worst subdivision isone of those problems he, being a student, failed to solve. So heasks you, a more successful CS student, to help him.
The traffic data are given in the form of matrix C, where Cij isthe amount of data sent between ith and jth nodes (Cij = Cji, Cii =0). The goal is to divide the network nodes into the two disjointedsubsets A and B so as to maximize the sum ∑Cij (i∈A,j∈B).

Input

The first line of input contains a number of nodes N (2<= N <= 20). The following N lines,containing N space-separated integers each, represent the trafficmatrix C (0 <= Cij <= 10000).
Output file must contain a single integer -- the maximum trafficbetween the subnetworks.

Output

Output must contain a single integer -- the maximum trafficbetween the subnetworks.

Sample Input

3

0 50 30

50 0 40

30 40 0

Sample Output

90

 

题意: 坏学生要破坏学校网络. 要找出两个A~B两个子网络的最大距离.

 

解题思路:

                 1.一开始却已为直接kruskal改一改最大生成树. 水之. (WA了一次.)

                 2.看了讨论,发现题意不是这回事.(T.T).

                 3. 还是深搜那回事.

         解析:

                (1). 深搜入口. 枚举节点node, 将所有的节点先归入第一个子网络.

                (2). 递归过程就是寻找最合适的分配节点的过程,这个就是深搜的思想.

                (3). 讨论上还有许许多多的剪枝方法.(有待我细看学习).

 

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 21

int grid[MAX][MAX];
int result;
int div[MAX];   //分成两个集合: 0 , 1(初始化为0).
int n;

void dfs(int node,int data)
{
    int cur =data;
    div[node] =1;
    for(int i =0; i < n;++i)    //记录当前的“最大”连通和.
    {
      if(div[i] == 0)
         cur += grid[i][node];
      else
         cur -= grid[i][node];
    }
    
    if(cur> result)
      result = cur;
      
    for(int i =node+1; i < n; ++i) //递归寻找合适的节点分配.
    {
      if(cur > data)
      {
         dfs(i,cur);
         div[i] = 0;
      }
    }
}

int main()
{
   freopen("input.txt","r",stdin);
   while(scanf("%d",&n) !=EOF)
    {
      for(int i = 0; i < n; ++i)
      {
         for(int j = 0; j < n; ++j)
         {
            scanf("%d",&grid[i][j]);
         }
      }
      
      result = 0;
      memset(div,0,sizeof(div));
      dfs(0,0);
      
      printf("%d\n",result);
    }
    
    return0;
}

0 0
原创粉丝点击