標籤:
Network Saboteur
| Time Limit: 2000MS |
|
Memory Limit: 65536K |
| Total Submissions: 9544 |
|
Accepted: 4542 |
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
題意:給出n個點(0-n-1),接下來n行,每行有n個數,第i行代表第i-1個數距離n個點的距離,問將這些點分為兩部分,兩個點集之間的權值最大值為多少。例如範例中講0,1,2分為兩部分(1,3)和(2)兩部分,則最長距離為map[1][2]+map[3][2]=90。
思路:怎麼想都沒看出這題和dfs有什麼關係,知道看了巨巨的題解,恍然大悟,漲姿勢了。首先我們將所有的店標記為0(即所有點放在一個集合裡),然後取出一個site標記為1(即將該點放在另一個集合裡),這是對於和site在一個集合裡的點,我們減去他們兩個之間的權值,對於不在一個集合裡的點,我們加上他們之間的權值。最後的結果為最大值。
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <algorithm>#include <set>#include <queue>#include <stack>using namespace std;const int inf=0x3f3f3f3f;int map[40][40];int g[40];int n,res;void dfs(int site,int sum){ int i; g[site]=1;//取出點 int num=sum; for(i=0;i<n;i++){ if(g[i]==1)//與site在一個集合裡的點 num-=map[site][i];//減去他們之間的權值 else//否則和site不在一個集合裡 num+=map[site][i];//加上他們之間的權值 } res=max(res,num);//依次迴圈結束找到的最大值 for(i=site+1;i<n;i++){//然後遍曆剩下的點 if(num>sum){//小剪枝,如果加入了點site後兩個集合之間的權值小了,則就不需要遍曆這個點。 dfs(i,num); g[i]=0; } }}int main(){ int i,j; while(~scanf("%d",&n)){ memset(map,0,sizeof(map)); memset(g,0,sizeof(g)); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&map[i][j]); res=-inf; dfs(0,0); printf("%d\n",res); } return 0;}
POJ 2531-Network Saboteur(dfs+剪枝)