POJ2531.Network Saboteur

试题请参见: 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章