LightOJ 1167 - Dangerous Tunnels 二分枚举+最大流

268人阅读 评论(0)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 220;
const int INF = 0x3f3f3f3f;
typedef long long ll;
struct edge
{
int to, cap, next;
}g[N*N*2];
int head[N], iter[N], level[N];
int n, m, cnt, _case = 0;
void add_edge(int v, int u, int cap)
{
g[cnt].to = u, g[cnt].cap = cap, g[cnt].next = head[v], head[v] = cnt++;
g[cnt].to = v, g[cnt].cap = 0, g[cnt].next = head[u], head[u] = cnt++;
}
bool bfs(int s, int t)
{
memset(level, -1, sizeof level);
level[s] = 0;
queue<int> que;
que.push(s);
while(! que.empty())
{
int v = que.front(); que.pop();
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && level[u] < 0)
{
level[u] = level[v] + 1;
que.push(u);
}
}
}
return level[t] == -1;
}
int dfs(int v, int t, int f)
{
if(v == t) return f;
for(int &i = iter[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && level[v] < level[u])
{
int d = dfs(u, t, min(g[i].cap, f));
if(d > 0)
{
g[i].cap -= d, g[i^1].cap += d;
return d;
}
}
}
return 0;
}
int dinic(int s, int t)
{
int flow = 0, f;
while(true)
{
if(bfs(s, t)) return flow;
while(f = dfs(s, t, INF),f > 0)
flow += f;
}
}
int main()
{
int t, k;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
int t1[N*N], t2[N*N], t3[N*N];
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", t1 + i, t2 + i, t3 + i);
if(t1[i] > t2[i]) swap(t1[i], t2[i]); //连边时从t1向t2连，要保证t1中转站高于t2对应中转站
}
scanf("%d", &k);
int l = 0, r = 100001, res = -1;
while(l <= r)
{
cnt = 0;
int mid = (l + r) >> 1;
for(int i = 1; i <= n; i++)
add_edge(i, i + n + 2, 1); //对中转站拆点连边，容量1
add_edge(0, 0 + n + 2, 10); //源点汇点拆点连边
add_edge(n + 1, n + 1 + n + 2, 10);
for(int i = 1; i <= m; i++)
if(t3[i] <= mid) //小于等于枚举值连边
add_edge(t1[i] + n + 2, t2[i], 1);
if(dinic(0, n + 1 + n + 2) >= k) r = mid - 1, res = mid;
else l = mid + 1;
}
if(res == -1) printf("Case %d: no solution\n", ++_case);
else printf("Case %d: %d\n", ++_case, res);
}
return 0;
}


个人资料
等级：
访问量： 17万+
积分： 7562
排名： 3483
~~~ACMER~~~
最新评论