题目描述
传送门
题解
感觉在考场上没做出来第一个原因是没有考虑这个转化:题目中的操作相当于是每一次选一条边,使它的权值+1. 然后我们可以发现,因为要保证id边一定在最小生成树上,所以就要保证将所有权值小于等于id的权值的边加到图里之后,id边的x和y不能连通。 那么就把id的x当成源点,y当成汇点,然后将所有权值小于id的边加进去,跑最小割就可以了。 注意加边的时候要双向加边,因为边的关系不确定。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
#define INF 2000000000
int n,m,id,maxflow;
struct hp{
int x,y,w;}edge[
805];
int tot,point[
505],nxt[
4000],v[
4000],remain[
4000];
int last[
505],num[
505],cur[
505],deep[
505];
queue <int> q;
inline void addedge(
int x,
int y,
int cap)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=
0;
}
inline void bfs(
int t)
{
for (
int i=
1;i<=n;++i) deep[i]=n;
deep[t]=
0;
for (
int i=
1;i<=n;++i) cur[i]=point[i];
while (!q.empty()) q.pop();
q.push(t);
while (!q.empty())
{
int now=q.front(); q.pop();
for (
int i=point[now];i!=-
1;i=nxt[i])
if (deep[v[i]]==n&&remain[i^
1])
{
deep[v[i]]=deep[now]+
1;
q.push(v[i]);
}
}
}
inline int addflow(
int s,
int t)
{
int now=t,ans=INF;
while (now!=s)
{
ans=min(ans,remain[last[now]]);
now=v[last[now]^
1];
}
now=t;
while (now!=s)
{
remain[last[now]]-=ans;
remain[last[now]^
1]+=ans;
now=v[last[now]^
1];
}
return ans;
}
inline void isap(
int s,
int t)
{
bfs(t);
for (
int i=
1;i<=n;++i) num[deep[i]]++;
int now=s;
while (deep[s]<n)
{
if (now==t)
{
maxflow+=addflow(s,t);
now=s;
}
bool has_find=
false;
for (
int i=cur[now];i!=-
1;i=nxt[i])
if (deep[v[i]]+
1==deep[now]&&remain[i])
{
has_find=
true;
last[v[i]]=i;
cur[now]=i;
now=v[i];
break;
}
if (!has_find)
{
int minn=n-
1;
for (
int i=point[now];i!=-
1;i=nxt[i])
if (remain[i]) minn=min(minn,deep[v[i]]);
if (!(--num[deep[now]]))
break;
num[deep[now]=minn+
1]++;
cur[now]=point[now];
if (now!=s) now=v[last[now]^
1];
}
}
}
int main()
{
scanf(
"%d%d%d",&n,&m,&id);
for (
int i=
1;i<=m;++i)
scanf(
"%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w);
tot=-
1;
memset(point,-
1,
sizeof(point));
memset(nxt,-
1,
sizeof(nxt));
for (
int i=
1;i<=m;++i)
if (edge[i].w<=edge[id].w&&i!=id)
{
addedge(edge[i].x,edge[i].y,edge[id].w-edge[i].w+
1);
addedge(edge[i].y,edge[i].x,edge[id].w-edge[i].w+
1);
}
isap(edge[id].x,edge[id].y);
printf(
"%d\n",maxflow);
}
总结
1、要学会转化和简化问题。 2、网络流还要熟练。
转载请注明原文地址: https://ju.6miu.com/read-1299295.html