POJ 2531 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
分析:深搜暴力枚举每种状态,找出最大值。
View Code
#include<stdio.h>
#include<string.h>
#define clr(x)memset(x,0,sizeof(x))
int max(int a,int b)
{
return a>b?a:b;
}
int v[22];
int g[22][22];
int n,res;
int dfs(int x,int k)
{
if(x==n+1)
return 0;
v[x]=k;
int i,tot=0,tmp1,tmp2;
for(i=1;i<x;i++)
if(v[i]!=v[x])tot+=g[i][x];
tmp1=dfs(x+1,1);
tmp2=dfs(x+1,2);
return max(tmp1,tmp2)+tot;
}
int main()
{
int i,j;
//freopen("D:ce.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&g[i][j]);
res=0;
int tmp1=dfs(1,1);
int tmp2=dfs(1,2);
res=max(tmp1,tmp2);
printf("%d\n",res);
}
return 0;
}
code2: 
View Code
#include<stdio.h>
#include<string.h>
int n,max;
int g[22][22];
int v[22];
void dfs(int x,int sum)
{
int i,t=sum;
v[x]=1;
for(i=1;i<=n;i++)
{
if(v[i]==0)
t+=g[x][i];
else t-=g[x][i];
}
if(t>max)
max=t;
for(i=x+1;i<=n;i++)
if(t>sum)
{
dfs(i,t);
v[i]=0;
}
}
int main()
{
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&g[i][j]);
max=0;
memset(v,0,sizeof(v));
dfs(1,0);
printf("%d\n",max);
return 0;
}

posted @ 2012-03-23 18:58  'wind  阅读(170)  评论(0编辑  收藏  举报