標籤:
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
30 50 3050 0 4030 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)