POJ-2531--Network Saboteur---DFS深搜

来源:互联网 发布:人类进化 知乎 编辑:程序博客网 时间:2024/06/03 11:57

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

题意:大概意思是给了一些点(题里说的当然不是点~),然后给出了它们的距离,然后把这些点划分到两个集合里,然后求两个点集之间的权值最大值。

解题思路:先把所有的点放在A集合里,然后不停的取出一个点x并把它标记放在另一个集合里,对于和x在一个集合里的点,我们减去他们两个之间的权值,对于不在一个集合里的点,我们加上他们之间的权值。最后的结果为最大值。

#include<iostream>#include<cstring>using namespace std;int flag[30];int s[30][30];int n;int sum;void dfs(int x,int d){    int num=d;    int i;    flag[x]=1;    for(i=1; i<=n; i++)    {        if(!flag[i])            num+=s[x][i];        else            num-=s[x][i];    }    if(num>sum)        sum=num;    for(i=x+1; i<=n; i++)    {        if(num>d)        {            dfs(i,num);            flag[i]=0;        }    }}int main(){    int i,j;    cin>>n;    for(i=1; i<=n; i++)        for(j=1; j<=n; j++)            cin>>s[i][j];    memset(flag,0,sizeof(flag));    dfs(1,0);    cout<<sum<<endl;}