【POJ2531】Network Saboteur(一道无需优化的DFS)

题面:【POJ2531】Network Saboteur

可以说,这道题是一道无需优化的DFS,由于N最大只有20,连O(2^n)的复杂度都能过,因此,只需要DFS枚举每一个节点分配到哪一个子集即可。

因此就能得出代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define LL long long
#define N 20
using namespace std;
int n,ans=0,len1=0,len2=0,s1[N+5],s2[N+5],a[N+5][N+5];
int read()
{
	int x=0,f=1;char ch=getchar();
	while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
	if(ch=='-') f=-1,ch=getchar();
	while(ch>='0'&&ch<='9') (x*=10)+=ch-'0',ch=getchar();
	return x*=f;
}
void write(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
void search(int x)
{
	if(x>n) {int t=0;for(int i=1;i<=len1;i++) for(int j=1;j<=len2;j++) t+=a[s1[i]][s2[j]];if(t>ans) ans=t;return;}//每个节点都分配完了,计算所需网络流量,并与ans比较 
	s1[++len1]=x,search(x+1),len1--,s2[++len2]=x,search(x+1),len2--;//枚举将该节点放入哪一个子集 
}
int main()
{
	n=read();
	for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j]=read();
	search(1);
	write(ans);
	return 0;
}



版权声明:转载请注明地址


猜你喜欢

转载自blog.csdn.net/chenxiaoran666/article/details/80028267
今日推荐