Description
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
Output file must contain a single integer -- the maximum traffic between the subnetworks.
Output
Sample Input
30 50 3050 0 4030 40 0Sample Output
90本題的重點是讀懂題意(大致意思就是給你一個集合,讓你把這個集合分爲兩個集合,求該集合使得:A集合中的每個元素到B集合中的每個元素之和最大) ,剛開始用dfs,裏面了兩個for循環就超時了。後來發現有簡便的算法,將一個新的數b添加進去,總的和的改變就是減少了原來A集合的每個數到b的距離,增加了b到B中其餘元素的距離,而A中的數是vis過的,所以只需要-map[i][b](i未已問過),+map[i][b](i未訪問過)即可;
下面爲DFS代碼(94ms):
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[22][22],vis[22],n,ans=0;
void dfs(int x,int sum)
{
vis[x]=1;
for(int i=0; i<n; i++)
{
if(vis[i])
sum-=a[x][i];
else
sum+=a[x][i];
}
if(sum>ans)
ans=sum;
for(int i=x+1; i<n; i++)
{
dfs(i,sum);
vis[i]=0;
}
return;
}
int main()
{
scanf("%d",&n);
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
scanf("%d",&a[i][j]);
dfs(0,0);
printf("%d\n",ans);
return 0;
}
然後,我發現,其實A集合中數的總數一直小於B也會成立,因爲A,B間是雙向的:
DFS2:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[22][22],b[22],vis[22],n,sum=0,ans=0;
void dfs(int x,int step,int sum)
{
vis[x]=1;
if(step==n/2+1)
return;
for(int i=0; i<n; i++)
{
if(vis[i])
sum-=a[x][i];
else
sum+=a[x][i];
}
if(sum>ans)
ans=sum;
for(int i=x+1; i<n; i++)
{
dfs(i,step+1,sum);
vis[i]=0;
}
return;
}
int main()
{
scanf("%d",&n);
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
scanf("%d",&a[i][j]);
dfs(0,0,0);
printf("%d\n",ans);
return 0;
}
遺憾的是,還是94ms,沒有變化,期待明天的BFS:
好的吧,我盡力了,這題不知道要怎麼用廣搜寫、、