ControlTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4727 Accepted Submission(s): 1962 Problem Description You, the head of Department of Security, recently received a top-secret information that a group of terrorists is planning to transport some WMD 1 from one city (the source) to another one (the destination). You know their date, source and destination, and they are using the highway network.
Input There are several test cases.
Output For each test case you should output exactly one line, containing one integer, the sum of cost of your selected set.
Sample Input 5 6 5 3 5 2 3 4 12 1 5 5 4 2 3 2 4 4 3 2 1
Sample Output 3 |
题意:
n个城市,m条双向边。现在有一群盗贼想从城市S到城市D,每个城市你都可以安排特工(当然需要一定的花费,特工不会白干活),当盗贼经过这个城市的时候就会被抓住,现在需要你花最少的钱安排特工,使得盗贼不管怎么走都会被抓住。
做法:
普通的最大流是边上带权,但是这道题的权值在点上,所以我们需要拆点把点拆开,当作是经过这个点就要花费这么多权值。本题把花费当作流量,就是要求最小割,因为最小割等于最大流,所以就是求最大流。
拆点就是把该点变成,边的权值就是该点的花费,表示如果要走到这个点,则一定要有这样的花费,再把a到b的边变成 和,表示如果要从b到a的话必须要先经过b点(即已经到b')。然后就是丢进dinic跑最大流。
#include<vector>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int Ni = 200005;
const int MAX = 1<<26;
struct Edge{
int u,v,c;
int next;
}edge[3*Ni];
int n,m;
int edn;//边数
int p[Ni];//父亲
int d[Ni];
int sp,tp;//原点,汇点
void addedge(int u,int v,int c){
edge[edn].u=u; edge[edn].v=v; edge[edn].c=c;
edge[edn].next=p[u]; p[u]=edn++;
edge[edn].u=v; edge[edn].v=u; edge[edn].c=0;
edge[edn].next=p[v]; p[v]=edn++;
}
int bfs(){
queue <int> q;
memset(d,-1,sizeof(d));
d[sp]=0;
q.push(sp);
while(!q.empty()){
int cur=q.front();
q.pop();
for(int i=p[cur];i!=-1;i=edge[i].next){
int u=edge[i].v;
if(d[u]==-1 && edge[i].c>0){
d[u]=d[cur]+1;
q.push(u);
}
}
}
return d[tp] != -1;
}
int dfs(int a,int b){
int r=0;
if(a==tp)return b;
for(int i=p[a];i!=-1 && r<b;i=edge[i].next)
{
int u=edge[i].v;
if(edge[i].c>0 && d[u]==d[a]+1)
{
int x=min(edge[i].c,b-r);
x=dfs(u,x);
r+=x;
edge[i].c-=x;
edge[i^1].c+=x;
}
}
if(!r)d[a]=-2;
return r;
}
int gainp(int x,int y){
return 2*x-y;
}
int dinic(int sp,int tp){
int total=0,t;
while(bfs()){
while(t=dfs(sp,MAX))
total+=t;
}
return total;
}
int main(){
int i,u,v,c,x;
while(~scanf("%d%d",&n,&m))
{
edn=0;//初始化
memset(p,-1,sizeof(p));
sp=0,tp=n*2+2;
scanf("%d%d",&u,&v);
addedge(sp,gainp(u,0),MAX);
addedge(gainp(v,1),tp,MAX);
for(int i=1;i<=n;i++){
scanf("%d",&c);
addedge(gainp(i,0),gainp(i,1),c);
}
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
addedge(gainp(u,1),gainp(v,0),MAX);
addedge(gainp(v,1),gainp(u,0),MAX);
}
printf("%d\n",dinic(sp,tp));
}
return 0;
}