题意:有一个N(<=2000)颗节点的树,每个点有权值,你有M(<=2000)个机器人,每个机器人i可以走s[i]到t[i]这段路收集权值并且最大携带不能超过w[i],问你能获得的最大权值
思路:一眼网络流是必然的,比赛的时候想歪了一下并且读错了一下题目导致我的做法会拆出8000个点来。。。正解应该是源点S连向树上的每个节点,流量为该点权值,汇点T连向每个机器人,流量为最大采集量,然后机器人可以走哪些路径就将它连向机器人的点,跑一次最大流即可
#include<bits/stdc++.h>
using namespace std;
const int maxn = 4005;
#define INF 1e9
struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic
{
int n,m,s,t;
vector<Edge>edges;
vector<int> G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void AddEdge(int from,int to,int cap)
{
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
void init(int nn)
{
for (int i = 0;i<=nn;i++)
G[i].clear();
edges.clear();
}
bool BFS()
{
memset(vis,0,sizeof(vis));
queue<int>q;
q.push(s);
d[s]=0;
vis[s]=1;
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = 0;i<G[x].size();i++){
Edge &e = edges[G[x][i]];
if (!vis[e.to] && e.cap>e.flow){
vis[e.to]=1;
d[e.to]=d[x]+1;
q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x,int a){
if (x==t || a==0)
return a;
int flow = 0,f;
for (int &i=cur[x];i<G[x].size();i++){
Edge&e = edges[G[x][i]];
if (d[x]+1==d[e.to] && (f=DFS(e.to,min(a,e.cap-e.flow)))>0){
e.flow+=f;
edges[G[x][i]^1].flow-=f;
flow+=f;
a-=f;
if (a==0)
break;
}
}
return flow;
}
int Maxflow(int s,int t)
{
this->s=s;
this->t=t;
int flow = 0;
while (BFS())
{
memset(cur,0,sizeof(cur));
flow+=DFS(s,INF);
}
return flow;
}
}di;
int n,m,s,t;
int a[maxn],fa[maxn],dep[maxn];
vector<int>e[maxn];
void dfs(int u,int f)
{
for(int i= 0;i<e[u].size();i++)
{
int v = e[u][i];
if(v==f)continue;
dep[v]=dep[u]+1;
fa[v]=u;
dfs(v,u);
}
}
void build()
{
memset(dep,0,sizeof(dep));
for(int i = 0;i<=n;i++)e[i].clear();
di.init(n+m+3);
s = 0;
t = n+m+2;
for(int i = 1;i<=n;i++)
{
scanf("%d",&a[i]);
di.AddEdge(s,i,a[i]);
}
for(int i = 1;i<=n-1;i++)
{
int u,v,w;
scanf("%d%d",&u,&v);
e[u].push_back(v);
e[v].push_back(u);
}
dfs(1,-1);
for(int i = 1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
di.AddEdge(i+n,t,w);
while(u!=v)
{
if(dep[v]>dep[u])
{
di.AddEdge(v,n+i,INF);
v = fa[v];
}
else
{
di.AddEdge(u,n+i,INF);
u=fa[u];
}
}
di.AddEdge(u,n+i,INF);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
build();
printf("%d\n",di.Maxflow(s,t));
}
}