poj2531 Network Saboteur

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
这题可以用深搜来做,有两个集合,默认刚开始所有的元素都在第一个集合,第一次我用dfs(num,sum)来做,num表示第二个集合的数字个数,sum表示当前状态的总和,但这么做超时了,后来想想因为这么做可能一个集合中1 2 3和2 3 1会重复出现,相当于效果相同的排序会重复出现,所以我换了一种思路,用dfs(id,sum)表示,id表示当前号码,整体表示把id加到第二个集合。递归过程中,每次从id+1开始循环,这样就避免了2 3 1这样的情况。最后用时266ms.


#include<stdio.h>
#include<string.h>
int map[30][30],value,vis[30],n;
void dfs(int id,int sum)         //把id号放入第二个集合 
{
	int i,j,x;
	x=sum;
	if(sum>value)value=sum;
	if(id>n)return;
	vis[id]=1;
	if(id!=0)
	{ for(i=1;i<=n;i++){
		if(vis[i]==0)x=x+map[i][id];
		else x=x-map[i][id];
	  }
	}
	for(i=id+1;i<=n;i++){
		dfs(i,x);
		vis[i]=0;
	}
}


int main()
{
	int m,i,j;
	while(scanf("%d",&n)!=EOF)
	{
	 for(i=1;i<=n;i++){
		for(j=1;j<=n;j++){
			scanf("%d",&map[i][j]);
		}
	 }
	 value=0;
	 memset(vis,0,sizeof(vis));
	 dfs(0,0);
	 printf("%d\n",value);
	}
	return 0;
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。