f[u]表示以u为根的最大连通集的总权值
AC代码
#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e3+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
#define ls (i<<1)
#define rs (i<<1|1)
#define fi first
#define se second
#define mk make_pair
#define mem(a,b) memset(a,b,sizeof(a))
LL read()
{
LL x=0,t=1;
char ch=getchar();
while(!isdigit(ch)){ if(ch=='-')t=-1; ch=getchar(); }
while(isdigit(ch)){ x=10*x+ch-'0'; ch=getchar(); }
return x*t;
}
struct edge
{
int from,to,next;
edge(){}
edge(int ff,int tt,int nn)
{
from=ff; to=tt; next=nn;
}
};
edge e[N<<1];
int head[N],f[N],ans,tot;
int x[N],y[N],w[N];
void add(int from,int to)
{
e[++tot]=edge(from,to,head[from]);
head[from]=tot;
}
inline void init(int n)
{
memset(head,0,sizeof(int)*(n+1));
tot=0;
}
void dfs(int u,int pre)
{
f[u]=w[u];
for(int i=head[u];i;i=e[i].next)
{
int v=e[i].to;// printf("u = %d,v = %d, pre = %d\n",u,v,pre);
if(v==pre) continue;
dfs(v,u);
f[u]+=max(f[v],0);
}
ans=max(ans,f[u]);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
init(n);
for(int i=1;i<=n;i++)
{
x[i]=read();
y[i]=read();
w[i]=read();
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(abs(x[i]-x[j])+abs(y[i]-y[j])==1)
add(i,j);
dfs(1,0);
printf("%d\n",ans);
}
}