先是最小费用流写~~超时,看了看别人的~~
两次最短路,把最短路上的边加入网络流图。再运行最大流。求最小割~~
#include <cstring>
#include <cstdio>
#include <queue>
#define MAXN 2000
#define MAXM 200000
#define inf 0x3f3f3f3f
using namespace std;
struct node
{
int u,v,f;
};
node e[MAXM*3];
int first[MAXN],next[MAXM*3];
int gap[MAXN],d[MAXN],curedge[MAXN],pre[MAXN];
int cc,inq[MAXN];
int d1[MAXN],d2[MAXN];
int first1[MAXN],first2[MAXN];
int next1[MAXM],next2[MAXM];
struct node1
{
int u,v;
int w;
};
node1 e1[MAXM],e2[MAXM];
void spfa(int s,int t)
{
memset(inq,0,sizeof(inq));
memset(d1,inf,sizeof(d1));
memset(d2,inf,sizeof(d2));
queue<int> q;
q.push(s);
d1[s]=0;
while(!q.empty())
{
int u=q.front();
q.pop();
inq[u]=0;
int i;
for(i=first1[u];i!=-1;i=next1[i])
{
int v=e1[i].v;
if(d1[v]>d1[u]+e1[i].w)
{
d1[v]=d1[u]+e1[i].w;
if(!inq[v])
{
inq[v]=1;
q.push(v);
}
}
}
}
memset(inq,0,sizeof(inq));
q.push(t);
d2[t]=0;
while(!q.empty())
{
int u=q.front();
q.pop();
inq[u]=0;
int i;
for(i=first2[u];i!=-1;i=next2[i])
{
int v=e2[i].v;
if(d2[v]>d2[u]+e2[i].w)
{
d2[v]=d2[u]+e2[i].w;
if(!inq[v])
{
inq[v]=1;
q.push(v);
}
}
}
}
}
inline void add_edge(int u,int v,int f)
{
e[cc].u=u;
e[cc].v=v;
e[cc].f=f;
next[cc]=first[u];
first[u]=cc;
cc++;
e[cc].u=v;
e[cc].v=u;
e[cc].f=0;
next[cc]=first[v];
first[v]=cc;
cc++;
}
int ISAP(int s,int t,int n)
{
int cur_flow,flow_ans=0,u,tmp,neck,i,v;
memset(d,0,sizeof(d));
memset(gap,0,sizeof(gap));
memset(pre,-1,sizeof(pre));
for(i=1;i<=n;i++)
curedge[i]=first[i];
gap[0]=n;
u=s;
while(d[s]<n)
{
if(u==t)
{
cur_flow=inf;
for(i=s;i!=t;i=e[curedge[i]].v)
{
if(cur_flow>e[curedge[i]].f)
{
neck=i;
cur_flow=e[curedge[i]].f;
}
}
for(i=s;i!=t;i=e[curedge[i]].v)
{
tmp=curedge[i];
e[tmp].f-=cur_flow;
e[tmp^1].f+=cur_flow;
}
flow_ans+=cur_flow;
u=neck;
}
for(i=curedge[u];i!=-1;i=next[i])
{
v=e[i].v;
if(e[i].f&&d[u]==d[v]+1)
break;
}
if(i!=-1)
{
curedge[u]=i;
pre[v]=u;
u=v;
}
else
{
if(0==--gap[d[u]])
break;
curedge[u]=first[u];
for(tmp=n+5,i=first[u];i!=-1;i=next[i])
if(e[i].f)
tmp=min(tmp,d[e[i].v]);
d[u]=tmp+1;
++gap[d[u]];
if(u!=s)
u=pre[u];
}
}
return flow_ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(first,-1,sizeof(first));
memset(next,-1,sizeof(next));
cc=0;
int n,m;
scanf("%d%d",&n,&m);
int i;
memset(first1,-1,sizeof(first1));
memset(first2,-1,sizeof(first2));
memset(next1,-1,sizeof(next1));
memset(next2,-1,sizeof(next2));
for(i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
e1[i].u=a;
e1[i].v=b;
e1[i].w=c;
next1[i]=first1[a];
first1[a]=i;
e2[i].u=b;
e2[i].v=a;
e2[i].w=c;
next2[i]=first2[b];
first2[b]=i;
}
int s,t;
scanf("%d%d",&s,&t);
spfa(s,t);
for(i=0;i<m;i++)
{
int u=e1[i].u;
int v=e1[i].v;
if(d1[u]+d2[v]+e1[i].w==d1[t])
{
add_edge(u,v,1);
}
}
int res=ISAP(s,t,1000);
printf("%d\n",res);
}
return 0;
}