POJ 2531 Network Saboteur DFS+剪枝

Network Saboteur
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 11694   Accepted: 5683

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

  题意就是给出一个无向带权图, 按顶点将顶点分为2个集合, 求这两个集合权值差值的最大值。
  首先创建一个g[]代表其中的一个集合, 当g[i] == 0 则不在这个集合内, g[i] == 1 则在这个集合里。
  void dfs( int site, int sum ); site代表当前拿进去的节点, sum代表前一个状态的两个集合的权值的差值。
  int num = sum;
  这时for一遍g[], 如果是一个集合内则减去这个权值( res -= map[i][site] )若不是一个集合则加上这个权值, 此时更新res的值( res = max( res, num ) )
  最后再遍历剩余的点, 这时候还有一个剪枝:
  如果, 如果这个点加入后权值变小了, 则没有必要加入当前这个点, ( if( num <= sum ) continue; )
  不剪枝可能会挂, 但是这道题的测试数据很水~

  
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3fffffff
using namespace std;

int res;
int map[25][25];
int g[30];
int n;

void dfs( int site, int sum ) {
    g[site] = 1;
    int num = sum;
    for( int i = 0; i < n; i++ ) {
        if( g[i] == 1 ) {
            num -= map[i][site];
        }
        else {
            num += map[i][site];
        }
    }
    res = max( res, num );
    for( int i = site + 1; i < n; i++ ) {
        if( num > sum ) {
            dfs( i, num );
            g[i] = 0;
        }
    }
    return;
}
int main() {
    while( cin >> n ) {
        res = -INF;
        memset( g, 0, sizeof(g) );
        memset( map, 0, sizeof(map) );
        for( int i = 0; i < n; i++ ) {
            for( int j = 0; j < n; j++ ) {
                cin >> map[i][j];
            }
        }
        dfs( 0, 0 );
        cout << res << endl;
    }
    return 0;
}
View Code

 

  剪枝是很重要的技巧, 另外以后不要光做这种套路题, 要多多做脑洞题, 开大自己的脑洞


posted on 2016-10-08 14:32  FriskyPuppy  阅读(2327)  评论(0编辑  收藏  举报

导航