https://blog.csdn.net/tzyshiwolaogongya/article/details/78565026
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
还是无法理解别人的代码以及这个DFS是如何遍历的,如何取出一个点,啥啥啥的
//先将所有节点标为0,即都在一个集合中
//然后依次取出一个结点标为1,意为放入另一个集合中,
//此时要更改sum值(sum减去与1在同一集合中的距离值,加上与1在不同集合中的距离值)
//如果sum比原答案大,则更新原答案,
//并且继续dfs枚举其余的点,注意dfs返回时辅助数组dep(dep记录每个点在0或1哪个集合中)要改回原值
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn = 30;
int n, ans;
int a[maxn][maxn];
int dep[maxn];
void dfs(int id, int data) {
dep[id] = 1;
int temp = data;
for (int i = 1; i <= n; i++) {
if (dep[i]) temp -= a[id][i];//如果在同一个集合减去他们两个之间的权值
else temp += a[id][i];//对于不在一个集合里的点,我们加上他们之间的权值
}
if (temp > ans) {
ans = temp;
}
if (temp > data) //只有当加入id这个结点去集合1使得data变大时,才接着id往下dfs
{
for (int i = id + 1; i <= n; i++) {
dfs(i, temp);
}
}
dep[id] = 0;
}
int main() {
while (~scanf_s("%d", &n)) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf_s("%d", &a[i][j]);
}
}
memset(dep, 0, sizeof(dep));
ans = 0;
dfs(1, 0);
printf("%d\n", ans);
}
return 0;
}