Optimal Milking
題目:
有K個機器,C只牛。要求求出最所有牛到各個產奶機的最短距離。給出一個C+K的矩陣,表示各種標號間的距離。
而每個地方最多有M只牛。
算法分析:
二分+最短路+網絡流
想法難以想到。我是看解題報告的思路。然後,自己上了手。開始wrong 了3次。後來各種該,無意的一個更改就AC了。無語勒。。。。
wrong 在了,網絡流建圖的時候只能是機器和奶牛之間的距離關系。而奶牛跟奶牛或者機器跟機器不要建邊。當時腦殘了!!!!
#include#include #include #include #include #include using namespace std; const int INF = 1 << 20; const int MAXN = 1000; struct Edge{ int from,to,cap,flow,cost; Edge(){}; Edge(int _from,int _to,int _cap,int _flow) :from(_from),to(_to),cap(_cap),flow(_flow){}; }; vector edges; vector G[MAXN]; int cur[MAXN],d[MAXN]; bool vst[MAXN]; int src,sink; int dist[MAXN][MAXN]; int K,C,M,V; void init(){ src = V + 1; sink = src + 1; for(int i = 0;i <= sink;++i) G[i].clear(); edges.clear(); } void flody(){ for(int k = 0;k < V;++k) for(int i = 0;i < V;++i) for(int j = 0;j < V;++j) if(dist[i][j] > dist[i][k] + dist[k][j]) dist[i][j] = dist[i][k] + dist[k][j]; // for(int i = 0;i < V;++i){ // for(int j = 0;j < V;++j) // printf("%d ",dist[i][j]); // puts(""); // } } void addEdge(int from,int to,int cap){ edges.push_back(Edge(from,to,cap,0)); edges.push_back(Edge(to,from,0,0)); int sz = edges.size(); G[from].push_back(sz - 2); G[to].push_back(sz - 1); } void build(int limit){ init(); for(int i = K;i < V;++i){ // 奶牛與源點 addEdge(src,i,1); } for(int i = 0;i < K;++i){ //機器與匯點 addEdge(i,sink,M); } //注意---> i = K!!! j < K!!!! for(int i = K;i < V;++i){ //奶牛與機器的連接 for(int j = 0;j < K;++j){ if(dist[i][j] <= limit){ addEdge(i,j,1); } } } } bool BFS(){ memset(vst,0,sizeof(vst)); queue Q; Q.push(src); d[src] = 0; vst[src] = 1; while(!Q.empty()){ int x = Q.front(); Q.pop(); for(int i = 0;i < (int)G[x].size();++i){ Edge& e = edges[G[x][i]]; if(!vst[e.to] && e.cap > e.flow){ vst[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vst[sink]; } int DFS(int x,int a){ if(x == sink||a == 0) return a; int flow = 0,f; for(int& i = cur[x];i < (int)G[x].size();++i){ Edge& e = edges[G[x][i]]; if(d[e.to] == d[x] + 1&&(f = DFS(e.to,min(a,e.cap - e.flow))) > 0){ e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int maxFlow(){ int flow = 0; while(BFS()){ memset(cur,0,sizeof(cur)); flow += DFS(src,INF); } return flow; } bool Check(int mid){ build(mid); int flow = maxFlow(); //cout << "flow : " << flow << endl; return flow == C; } void solve(){ flody(); int lb = -1,ub = INF + 100; while(ub - lb > 1){ int mid = (lb + ub) / 2; if(Check(mid)) ub = mid; else lb = mid; //cout << "mid: " << mid << " lb: " << lb << " ub: " << ub << endl; } printf("%d\n",ub); } int main() { // freopen("Input.txt","r",stdin); while(~scanf("%d%d%d",&K,&C,&M)){ V = K + C; int x; for(int i = 0;i < V;++i){ for(int j = 0;j < V;++j){ scanf("%d",&x); dist[i][j] = (x == 0 ? INF : x); } dist[i][i] = 0; } solve(); } return 0; }