比赛 20120705 评测结果 AAAAAAAAAA
题目名称 塔防游戏 最终得分 100
用户昵称 CC 运行时间 0.000 s
代码语言 C++ 内存使用 0.00 MiB
提交时间 2012-07-05 11:47:11
显示代码纯文本
#include <cstdio>
#include <algorithm>
#include <cstring>
#define INF 1000000000
struct edge {
	int y,v;
	edge *next,*opt;
	edge (int y,int v,edge *next): y(y),v(v),next(next) {};
}*a[1005],*pre[1005],*t[1005];
int n,m,S,T;
int level[1005],dis[1005];
void create(int x,int y,int v) {
	t[x] = new edge(y,v,t[x]);
	t[y] = new edge(x,0,t[y]);
	t[x]->opt = t[y];t[y]->opt = t[x];
}
void spfa() {
	int q[100000] = {0},head = 0,tail = 0;
	bool inq[1005] = {0};
	for (int i = 1;i <= n;i++) dis[i] = INF;
	q[0] = S;
	inq[S] = 1;
	dis[S] = 0;
	while (head <= tail) {
		int now = q[head++];
		for (edge *p = a[now];p;p = p->next) {
				if (dis[p->y] == dis[now] + p->v) 
					pre[p->y] = new edge(now,0,pre[p->y]);
				if (dis[p->y] > dis[now] + p->v) {
					dis[p->y] = dis[now] + p->v;
					pre[p->y] = NULL;
					pre[p->y] = new edge(now,0,pre[p->y]);
					if (!inq[p->y]) inq[q[++tail] = p->y] = 1;
				}
		}
		inq[now] = 0;
	}
}
void bfs1() {
	int q[100000] = {0},head = 0,tail = 0;
	bool done[1005] = {0};
	q[0] = T;
	done[T] = 1;
	while (head <= tail) {
		int now = q[head++];
		for (edge *p = pre[now];p;p = p->next) {
			create(now,p->y,1);
			if (!done[p->y]) q[++tail] = p->y;
			done[p->y] = 1;
		}
	}
}
bool bfs() {
	int head = 0,tail = 0,q[100000] = {0};
	memset(level,-1,sizeof(level));
	q[0] = T;
	level[T] = 0;
	while (head <= tail) {
		int now = q[head++];
		for (edge *p = t[now];p;p = p->next)
			if (level[p->y] == -1 && p->v) 
				level[q[++tail] = p->y] = level[now] + 1;
	}
	return level[S] != -1;
}
int extend(int u,int sum) {
	int o = 0,tmp = 0;
	if (u == S) return sum;
	for (edge *p = t[u];p && o < sum;p = p->next)
		if (level[p->y] == level[u] + 1 && p->v) {
			tmp = p->v;
			if (tmp > sum - o) tmp = sum - o;
			tmp = extend(p->y,tmp);
			o += tmp;p->v -= tmp;p->opt->v += tmp;
		}
	if (!o) level[u] = -1;
	return o;
}
inline int dinic() {
	int tmp = 0,u = 0;
	while (bfs())
		while ((u = extend(T,INF)))
			tmp += u;
	return tmp;
}
int main() {
	freopen("defence.in","r",stdin);
	freopen("defence.out","w",stdout);
	scanf("%d%d%d%d", &n, &m, &S, &T);
	int p,q,r;
	for (int i = 1;i <= m;i++) {
		scanf("%d%d%d", &p, &q, &r);
		a[p] = new edge(q,r,a[p]);
		a[q] = new edge(p,r,a[q]);
	}
	spfa();
	bfs1();
	int ans = dinic();
	printf("%d\n", ans);
	return 0;
}