POJ 2531 Network Saboteur(DFS分两点集求最大权)

Network Saboteur
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 9522 Accepted: 4524

Description

A university network is composed of N computers. System administrators gathered information on the traffic between nodes, and carefully divided the network into two subnetworks in order to minimize traffic between parts. 
A disgruntled computer science student Vasya, after being expelled from the university, decided to have his revenge. He hacked into the university network and decided to reassign computers to maximize the traffic between two subnetworks. 
Unfortunately, he found that calculating such worst subdivision is one of those problems he, being a student, failed to solve. So he asks you, a more successful CS student, to help him. 
The traffic data are given in the form of matrix C, where Cij is the amount of data sent between ith and jth nodes (Cij = Cji, Cii = 0). The goal is to divide the network nodes into the two disjointed subsets 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 traffic matrix C (0 <= Cij <= 10000). 
Output file must contain a single integer -- the maximum traffic between the subnetworks. 

Output

Output must contain a single integer -- the maximum traffic between the subnetworks.

Sample Input

3
0 50 30
50 0 40
30 40 0

Sample Output

90
 
给出邻接矩阵,问将这些点分成两部分,两个点集之间的权值最大为多少?
如样例,将1,2,3三个点分成[1,3]和[2]两部分,所以结果为a[1][2]+a[3][2]=90。
虽然这题是放在DFS里面,但我想了很久,还是没想到怎么用DFS来做,后来看了别人的博客,又涨姿势了。。。
一开始我们把所有的点都标记为0,即把他们放在一个点集里,我们可以从中取出一个点x标记为1,即把它放在另一个集合里,这时对于和点x在一个集合中的点,我们要减去它俩之间的权值,不在一个集合中的点要加上它们之间的权值,最后的结果就是其中的一个最大值。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stdlib.h>
#include <algorithm>
#define inf 0x7fffffff
#define N 35
using namespace std;
int n,ans;
int a[N][N];
int s[N];
void dfs(int x,int sum)
{
    s[x]=1;                      //取出点x
    int y=sum;
    for(int i=1; i<=n; i++)
    {
        if(s[i]==1)                //在同一个集合中,减去他们的权值
            y-=a[x][i];
        else y+=a[x][i];
    }
    ans=max(y,ans);
    for(int i=x+1; i<=n; i++)
    {
        if(y>sum)               //如果加入了点x后,两集合之间的权值反而小了,这种情况可以直接去掉
        {                       //如果去掉if这个判断 157MS ,,反之12MS
            dfs(i,y);
            s[i]=0;
        }
    }
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                scanf("%d",&a[i][j]);
        memset(s,0,sizeof(s));
        ans=-1;
        dfs(1,0);
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值