Network Saboteur(dfs+剪枝)

来源:互联网 发布:关于淘宝开店 编辑:程序博客网 时间:2024/05/29 03:17
Network Saboteur
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 12305 Accepted: 5939

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

30 50 3050 0 4030 40 0

Sample Output

90

Source


题目意思:给出n个点,输入Cij表示从点i到点j的值为Cij.现要要把n个点分成两部分A集合,B集合,求A中的每个点到B中的每个点的总和值最大。
分析:假设有10个点,点i位置为1则在A集合,为0在B集合。

    位置    1   2   3   4   5   6   7   8   9   10

 第一种     1   1   1    1   1   1   1   1   1   0

        1   1   1    1   1   1   1   1   0   1

        1   1   1    1   1   1    1   1  0   0

    ..........................................

最后一种:  0   0    0    0   0   0    0   0   0  0


思路:DFS思路:
1、把这两个集合标记为0和1,先默认所有点都在集合0里。
2、依次枚举每个点id,把每个点都放到集合1里去,这个时候就要调整集合的权值了,原来和id都在集合0里的点,要把权值加上;而在集合1里的点,要把权值减去。
3、权值调整完毕后,和ans比较,如果比ans要大, 调整ans。
4、如果放到集合1中,调整节点后的权值比放在集合0中要大,那么就默认这个点在集合1中,继续枚举下面的点进行DFS。最终是可以把最有状态都枚举出来的。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int mp[25][25],del[25];int ans=0,n;void dfs(int id,int max){    del[id]=1;//把id放入集合b    int temp=max;    for(int i=1;i<=n;i++)    {        if(!del[i])        {           temp+=mp[i][id];//该点在集合a中不在b中加上距离        }        else        temp-=mp[i][id];//该点和id都在b中减去距离    }    if(temp>ans)    ans=temp;    for(int i=id+1;i<=n;i++)    {        if(temp>max)//只有把该点放入集合b后得到的距离更大才继续往下递归        {           dfs(i,temp);           del[i]=0;//回溯        }    }}int main(){    scanf("%d",&n);    memset(mp,0,sizeof(mp));    for(int i=1;i<=n;i++)    {        for(int j=1;j<=n;j++)        {            scanf("%d",&mp[i][j]);        }    }    memset(del,0,sizeof(del));    dfs(1,0);    printf("%d\n",ans);    return 0;}


0 0