记录编号 393677 评测结果 AAAAAAAAAA
题目名称 运输问题4 最终得分 100
用户昵称 GravatarHeHe 是否通过 通过
代码语言 C++ 运行时间 0.012 s
提交时间 2017-04-11 20:47:15 内存使用 0.31 MiB
显示代码纯文本
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int MAXN = 110, INF = 0x7fffffff;

inline int in(void){
	char tmp = getchar();
	int res = 0;
	while(!isdigit(tmp))tmp = getchar();
	while(isdigit(tmp))
		res = (res + (res << 2) << 1) + (tmp ^ 48),
		tmp = getchar();
	return res;
}

struct EDGE{
	int fr, to, ne;
	int cap, w;

	EDGE(){;}
	EDGE(int a, int b, int c, int d, int e){
		fr = a, to = b, ne = c, cap = d, w = e;
	}
};

inline void add_edge(int fr, int to, int cap, int w);
bool SPFA(void);
inline int get_flow(void);

vector<EDGE> edge;
int head[MAXN];
bool inq[MAXN];
int dis[MAXN], pre[MAXN];
int N, a, b, S, T, ans;

int main(){ 
#ifndef LOCAL
	freopen("maxflowd.in", "r", stdin);
	freopen("maxflowd.out", "w", stdout);
#endif
	memset(head, 0xff, sizeof(head));
	
	N = in(), S = in(), T = in();
	for(int i = 1; i <= N; ++i){
		for(int j = 1; j <= N; ++j){
			a = in(), b = in();
			if(a != 0)add_edge(i, j, a, b);
		}
	}
	
	while(SPFA()){
		ans += dis[T] * get_flow();
	}

	printf("%d\n", ans);

	return 0;
}

inline void add_edge(int fr, int to, int cap, int w){
	edge.push_back(EDGE(fr, to, head[fr], cap, w)), head[fr] = edge.size() - 1;
	edge.push_back(EDGE(to, fr, head[to], 0, -w)), head[to] = edge.size() - 1;
	return ;
}

bool SPFA(void){
	memset(dis, 0x7f, sizeof(dis));
	memset(inq, 0x00, sizeof(inq));
	memset(pre, 0xff, sizeof(pre));
	queue<int> que;
	int now, to;

	que.push(S);
	dis[S] = 0;
	inq[S] = true;

	while(!que.empty()){
		now = que.front();
		que.pop();
		inq[now] = false;
		for(int i = head[now]; i != -1; i= edge[i].ne){
			to = edge[i].to;
			if(edge[i].cap && dis[now] + edge[i].w  < dis[to]){
				dis[to] = dis[now] + edge[i].w;
				pre[to] = i;
				if(inq[to])continue;
				que.push(to);
				inq[to] = true;
			}
		}
	}

	return pre[T] != -1;
}

inline int get_flow(void){
	int now = pre[T], min_flow = INF;
	while(now != -1){
		min_flow = min(min_flow, edge[now].cap);
		now = pre[edge[now].fr];
	}

	now = pre[T];
	while(now != -1){
		edge[now].cap -= min_flow;
		edge[now ^ 1].cap += min_flow;
		now = pre[edge[now].fr];
	}

	return min_flow;
}