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;
}