# 【bzoj2238】Mst 最小生成树+树链剖分+线段树

Q行，对于每个询问输出对应最小生成树的边权和的值，如果图不连通则输出“Not connected”

4 4
1 2 3
1 3 5
2 3 9
2 4 1
4
1
2
3
4

15
13
9
Not connected

#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 50010
#define lson l , mid , x << 1
#define rson mid + 1 , r , x << 1 | 1
using namespace std;
struct data
{
int x , y , z , id;
bool vis;
}a[N << 1];
int f[N] , head[N] , to[N << 1] , val[N << 1] , next[N << 1] , cnt , ref[N << 1] , fa[N] , deep[N] , si[N] , bl[N] , pos[N] , tot , mn[N << 2] , n;
bool cmp1(const data &a , const data &b)
{
return a.z < b.z;
}
bool cmp2(const data &a , const data &b)
{
return a.id < b.id;
}
int find(int x)
{
return x == f[x] ? x : f[x] = find(f[x]);
}
void add(int x , int y , int z)
{
to[++cnt] = y , val[cnt] = z , next[cnt] = head[x] , head[x] = cnt;
}
void dfs1(int x)
{
int i;
si[x] = 1;
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x])
fa[to[i]] = x , deep[to[i]] = deep[x] + 1 , ref[val[i]] = to[i] , dfs1(to[i]) , si[x] += si[to[i]];
}
void dfs2(int x , int c)
{
int i , k = 0;
bl[x] = c , pos[x] = ++tot;
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x] && si[to[i]] > si[k])
k = to[i];
if(k)
{
dfs2(k , c);
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x] && to[i] != k)
dfs2(to[i] , to[i]);
}
}
void update(int b , int e , int a , int l , int r , int x)
{
if(b <= l && r <= e)
{
mn[x] = min(mn[x] , a);
return;
}
int mid = (l + r) >> 1;
if(b <= mid) update(b , e , a , lson);
if(e > mid) update(b , e , a , rson);
}
int query(int p , int l , int r , int x)
{
if(l == r) return mn[x];
int mid = (l + r) >> 1;
if(p <= mid) return min(mn[x] , query(p , lson));
else return min(mn[x] , query(p , rson));
}
void modify(int x , int y , int v)
{
while(bl[x] != bl[y])
{
if(deep[bl[x]] < deep[bl[y]]) swap(x , y);
update(pos[bl[x]] , pos[x] , v , 1 , n , 1) , x = fa[bl[x]];
}
if(deep[x] > deep[y]) swap(x , y);
if(x != y) update(pos[x] + 1 , pos[y] , v , 1 , n , 1);
}
int main()
{
int m , q , i , sum = 0 , x , v , c = 0;
scanf("%d%d" , &n , &m);
for(i = 1 ; i <= m ; i ++ ) scanf("%d%d%d" , &a[i].x , &a[i].y , &a[i].z) , a[i].id = i;
sort(a + 1 , a + m + 1 , cmp1);
for(i = 1 ; i <= n ; i ++ ) f[i] = i;
for(i = 1 ; i <= m ; i ++ )
if(find(a[i].x) != find(a[i].y))
sum += a[i].z , a[i].vis = 1 , add(a[i].x , a[i].y , a[i].id) , add(a[i].y , a[i].x , a[i].id) , f[f[a[i].x]] = f[a[i].y] , c ++ ;
if(c < n - 1)
{
scanf("%d" , &q);
while(q -- ) puts("Not connected");
return 0;
}
dfs1(1) , dfs2(1 , 1);
memset(mn , 0x3f , sizeof(mn));
sort(a + 1 , a + m + 1 , cmp2);
for(i = 1 ; i <= m ; i ++ )
if(!a[i].vis)
modify(a[i].x , a[i].y , a[i].z);
scanf("%d" , &q);
while(q -- )
{
scanf("%d" , &x);
if(!a[x].vis) printf("%d\n" , sum);
else
{
v = query(pos[ref[x]] , 1 , n , 1);
if(v == 0x3f3f3f3f) puts("Not connected");
else printf("%d\n" , sum - a[x].z + v);
}
}
return 0;
}


posted @ 2017-09-26 19:51  GXZlegend  阅读(712)  评论(0编辑  收藏  举报