試題請參見: http://poj.org/problem?id=2531
題目概述
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).
解題思路
簡單深度優先搜索(回溯).
將最終結果劃分爲兩個集合, 可見就是回溯, 對於每1個節點先假設放在第1個子網中, 計算流量的總和, 再放在第2個子網中計算流量總和.
遇到的問題
沒遇到什麼問題, 除了一開始把 currentTraffic += ...
寫成了 currentTraffic = ...
.
源代碼
#include <iostream>
const size_t MAX_NODES = 20;
int traffic[MAX_NODES][MAX_NODES] = {0};
int subnet1Index = 0, subnet2Index = 0;
int subnet1[MAX_NODES] = {0};
int subnet2[MAX_NODES] = {0};
void getMaxTraffic(int currentNode, int totalNodes, int &maxTraffic) {
if ( currentNode == totalNodes ) {
int currentTraffic = 0;
for ( int i = 0; i < subnet1Index; ++ i ) {
for ( int j = 0; j < subnet2Index; ++ j ) {
currentTraffic += traffic[subnet1[i]][subnet2[j]];
}
}
if ( currentTraffic > maxTraffic ) {
maxTraffic = currentTraffic;
}
} else {
subnet1[subnet1Index ++] = currentNode;
getMaxTraffic(currentNode + 1, totalNodes, maxTraffic);
-- subnet1Index;
subnet2[subnet2Index ++] = currentNode;
getMaxTraffic(currentNode + 1, totalNodes, maxTraffic);
-- subnet2Index;
}
}
int main() {
int n = 0, maxTraffic = 0;
std::cin >> n;
for ( int i = 0; i < n; ++ i ) {
for ( int j = 0; j < n; ++ j ) {
std::cin >> traffic[i][j];
traffic[j][i] = traffic[i][j];
}
}
getMaxTraffic(0, n, maxTraffic);
std::cout << maxTraffic << std::endl;
return 0;
}