链接;http://acm.hdu.edu.cn/showproblem.php?pid=6582
题意:给你一个图,要求你减去一些边使得1至n的最短路径变长。并且使得花费最小,删边花费为其长度。
思路:先求出最短路,将所有的最短路的边新建一个图,跑一个最大流就可以了。
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <map>
#include <set>
#include <bitset>
#include <stack>
#define ull unsigned long long
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mems(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const ll mod=998244353;
const int N=1e5+10;
const double pi=acos(-1);
const int inf=0x3f3f3f3f;
const int M=50000+5;
ll dis[N];
ll cnt,cn;
ll T;//网络流汇点
ll head[N];
bool vis[N];
struct nod//最短路
{
ll u,v,w,next;
} se[N*2];
void add(ll u,ll v,ll w)//最短路建图
{
se[cnt]=(nod)
{
u,v,w,head[u]
};
head[u]=cnt++;
}
void spfa(ll ss)//单源最短路
{
vis[ss]=1;
dis[ss]=0;
queue<ll>q;
q.push(ss);
while(!q.empty())
{
ll u=q.front();
q.pop();
vis[u]=0;
for(ll i=head[u]; ~i; i=se[i].next)
{
ll v=se[i].v;
ll w=se[i].w;
if(dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
}
struct node//最大流
{
ll v,cap,to;
} s[N];
ll hea[N];
void add1(ll u,ll v,ll cap)//最大流建图
{
s[cn].v=v;
s[cn].cap=cap;
s[cn].to=hea[u];
hea[u]=cn++;
s[cn].v=u;
s[cn].cap=0;
s[cn].to=hea[v];
hea[v]=cn++;
}
ll dist[N];
bool bfs()
{
memset(dist,0,sizeof(dist));
queue<ll>q;
dist[1]=1;
q.push(1);
while(!q.empty())
{
ll u=q.front();
q.pop();
for(ll e=hea[u]; ~e; e=s[e].to)
{
ll v=s[e].v,cap=s[e].cap;
if(dist[v]==0&&cap>0)
{
dist[v]=dist[u]+1;
q.push(v);
}
}
}
return dist[T]!=0;
}
ll dfs(ll u,ll flow)
{
ll mm;
if(u==T)
return flow;
for(ll e=hea[u]; ~e; e=s[e].to)
{
ll v=s[e].v,cap=s[e].cap;
if(dist[v]==dist[u]+1&&cap>0&&(mm=dfs(v,min(cap,flow))))
{
s[e].cap-=mm;
s[e^1].cap+=mm;
return mm;
}
}
dist[u]=-1;//注意这里
return 0;
}
ll dinic()
{
ll ans=0,tf;
while(bfs())
{
// printf("*\n");
while(tf=dfs(1,inf))
{
// printf("%lld\n",tf);
ans+=tf;
}
}
return ans;
}
void init()
{
cnt=0;
cn=0;
mems(head,-1);
mems(hea,-1);
mems(dis,inf);
mems(vis,0);
}
int main()
{
ll t;
scanf("%lld",&t);
while(t--)
{
init();
ll n,m;
scanf("%lld%lld",&n,&m);
for(ll i=1; i<=m; i++)
{
ll a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
add(a,b,c);
}
spfa(1);
for(ll i=1; i<=n; i++)
{
for(ll j=head[i]; ~j; j=se[j].next)
{
ll v=se[j].v;
ll w=se[j].w;
if(dis[v]-dis[i]==w)
{
// printf("%lld-> %lld==%lld\n",i,v,w);
add1(i,v,w);
}
}
}
T=n;
printf("%lld\n",dinic());
}
return 0;
}