LightOJ - 1404 Sending Secret Messages(最小费用最大流)
生活随笔
收集整理的這篇文章主要介紹了
LightOJ - 1404 Sending Secret Messages(最小费用最大流)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一張由n個點和m條邊組成的無向帶權圖,并且每個單位的權值都附加著一個花費,現在要求從點1到點n傳輸大小為p的數據,最小需要多少花費
題目分析:最小費用最大流的模板題目,只不過需要稍微修改內部實現,因為普通的最小費用最大流的前提是令源點到匯點的流量最大,其次為費用最小,因為這個題目給出了一個前提,就是讓流量達到p即可,并不需要達到最大,這樣根據題意稍微修改一下模板的代碼就好了,記得特判一下impossible的情況
代碼:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=55;//點const int M=N*N*2;//邊struct Edge {int to,w,cost,next; }edge[M];int head[N],cnt,flow;void addedge(int u,int v,int w,int cost) {edge[cnt].to=v;edge[cnt].w=w;edge[cnt].cost=cost;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;edge[cnt].cost=-cost;edge[cnt].next=head[v];head[v]=cnt++; }int d[N],incf[N],pre[N];bool vis[N];bool spfa(int s,int t) {memset(d,inf,sizeof(d));memset(vis,false,sizeof(vis));memset(pre,-1,sizeof(pre));queue<int>q;q.push(s);vis[s]=true;incf[s]=inf;d[s]=0;while(!q.empty()){int u=q.front();q.pop();vis[u]=false;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;int cost=edge[i].cost;if(!w)continue;if(d[v]>d[u]+cost){d[v]=d[u]+cost;pre[v]=i;incf[v]=min(incf[u],w);if(!vis[v]){vis[v]=true;q.push(v);}}}}return pre[t]!=-1; }int update(int s,int t) {int x=t;while(x!=s){int i=pre[x];edge[i].w-=incf[t];edge[i^1].w+=incf[t];x=edge[i^1].to;}flow=min(flow,incf[t]);return d[t]*flow; }void init() {memset(head,-1,sizeof(head));cnt=0; }int solve(int st,int ed,int p) {int ans=0;while(p){flow=p;if(spfa(st,ed)){ans+=update(st,ed);p-=flow;}elsereturn -1;}return ans; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int w;cin>>w;int kase=0;while(w--){init();int n,m,p;scanf("%d%d%d",&n,&m,&p);while(m--){int u,v,w,cost;scanf("%d%d%d%d",&u,&v,&w,&cost);addedge(u,v,w,cost);addedge(v,u,w,cost);}int ans=solve(1,n,p);if(ans==-1)printf("Case %d: impossible\n",++kase);elseprintf("Case %d: %d\n",++kase,ans);}return 0; }?
總結
以上是生活随笔為你收集整理的LightOJ - 1404 Sending Secret Messages(最小费用最大流)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 78E Eva
- 下一篇: LightOJ - 1243 Guard