题意:有n个点m条边,问如果删掉一条边使图不连通,问最少需要多少兵力。每条边都有驻守的士兵,如果想删掉这条边至少要派相同人数的士兵。
思路:就是一个连通图求最小权的桥的问题。
桥的概念:无向连通图中,删掉某条边可以使原图不连通,那么该边就是无向图的桥。
tarjan算法求桥的思想简单说一下:以任意一点开始建立搜索树,记录每个点的搜索深度dep和非父子边能到达的最早节点深度low,就是说这条路上可能有一个环,这个环里的最小的搜索深度就是low,如果没有环,那么dep=low(父子边成环)。
解题思路:这个题比较裸但是坑点比较多,首先图可能是不连通的,要先判断一下,我是用的并查集,如果本身就不连通,输出0即可;如果某条边守卫为0,也应该派1个被炸药的过去。。。
写了个模板留着以后用。
PS:这个题的内存限制开的有点小,应该说网上大部分题解的代码都过不了,因为边最多有100w条,记双向边又要200w,一个结构体或类里存4~5个int,能过才有鬼。
之所以没有mle是因为hdoj的判题机制貌似是看程序运行实际用到了多少内存,而不是声明了多少内存。
(我也没别的意思就是吐槽一下因为我太蠢写了个没用的memset结果mle了好久。。。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int M = 1005;
struct Edge{
int to, next, id, val;
Edge(){}
Edge(int a, int b, int c, int d): to(a), next(b), id(c), val(d){}
}edge[M * M * 2];
int _next[M], edgeCnt, dep[M], low[M], nowdep, bridge[M * M * 2];
bool isBridge[M * M];
void addEdge(int from, int to, int val, int id){
edge[++edgeCnt] = Edge(to, _next[from], id, val);
_next[from] = edgeCnt;
edge[++edgeCnt] = Edge(from, _next[to], id, val);
_next[to] = edgeCnt;
}
void tarjanInit(){
memset(dep, 0, sizeof dep);
memset(low, 0, sizeof low);
memset(isBridge, 0, sizeof isBridge);
nowdep = 0;
}
void tarjan(int from, int id) {
dep[from] = low[from] = ++nowdep;
for(int i = _next[from]; i; i = edge[i].next){
if(edge[i].id == id) continue;
int to = edge[i].to;
if(!dep[to]){
tarjan(to, edge[i].id);
low[from] = min(low[from], low[to]);
if(dep[from] < low[to]) isBridge[i] = true;
}
else low[from] = min(low[from], dep[to]);
}
}
int tarjanGetBridge() {
tarjanInit();
tarjan(1, 0);
int cnt = 0;
for(int i = 1; i <= edgeCnt; i++)
if(isBridge[i]) bridge[cnt++] = i;
return cnt;
}
/
int father[M];
void init() {
for(int i = 1; i <= M; i++) father[i] = i;
// memset(edge, 0, sizeof edge);(╯‵□′)╯︵┴─┴
memset(_next, 0, sizeof _next);
edgeCnt = 0;
}
int getfather(int a) {
return a == father[a] ? a : father[a] = getfather(father[a]);
}
int unit(int a, int b){
int t1 = getfather(a), t2 = getfather(b);
father[t1] = min(t1, t2);
father[t2] = min(t1, t2);
}
main() {
int n, m;
while(~scanf("%d %d", &n, &m)){
if(n == 0 && m == 0) break;
init();
for(int i = 1; i <= m; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
addEdge(a, b, c, i);
unit(a, b);
}
bool flag = true;
for(int i = 1; i <= n; i++) if(getfather(i) != father[1]) flag = false;
if(!flag){
puts("0");
continue;
}
int cnt = tarjanGetBridge();
int ans = 0x7fffffff;
for(int i = 0; i < cnt; i++) {
ans = min(ans, edge[bridge[i]].val);
}
if(ans == 0) puts("1");
else if(ans == 0x7fffffff) puts("-1");
else printf("%d\n", ans);
}
}