码迷,mamicode.com
首页 > Web开发 > 详细

CSU-ACM2016暑假集训训练2-DFS(C - Network Saboteur)

时间:2016-07-23 00:42:47      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

C - Network Saboteur

Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

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,B两个集合,使得A集合中的所有顶点到B集合所有顶点的距离之和为最大。
首先两个集合的表示用一个一维数组A[],其中A[i]=1,表示节点i在集合A中,为0则在集合B中。
二位数组C[][]存储邻接矩阵,
由于每一个数字有两种选择0和1,结构适用深度优先:从第一个数开始A[0]=1(假设0号顶点一定在集合A中),
对0来说第2个顶点有两种情况,依次类推,结构就出来了。递归出口就是到达第n-1号顶点。
求和用两个for循环加上对存在集合的判定,记录最大值,每次求和结果与最大值比较,如果更大则修改最大值。

收获感想:对深度优先有了更深刻的理解,刚开始编写的时候思路有点混乱,不知道怎么写递归,出口也搞错了,一遍遍的过程中深入理解。
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
int A[21],B[21],C[21][21],N,sum,tp=0,tp2=0;
void bfs(int tp,int l);
int main()
{
    memset(A,0,21);
    //memset(B,-1,21);

    while(scanf("%d",&N)!=EOF){
    for(int i=0;i<N;i++)
    for(int j=0;j<N;j++)
    scanf("%d",&C[i][j]);
    bfs(0,1);
    printf("%d\n",sum);
    }

    return 0;
}

void bfs(int tp,int l)
{
    if(tp==N||tp==-1) return;
    int s=0;
    A[tp]=l;
    for(int i=0;i<N;i++)
    {
        if(A[i]==1)
        for(int j=0;j<N;j++)
        {
            if(A[j]==0)
            s=s+C[i][j];

        }
    }
    if(sum<s) sum=s;
    bfs(tp+1,1);
    bfs(tp+1,0);
}

 

CSU-ACM2016暑假集训训练2-DFS(C - Network Saboteur)

标签:

原文地址:http://www.cnblogs.com/hr974041087/p/5697528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!