【最小树形图】bzoj 2753 滑雪与时间胶囊

来源:互联网 发布:淘宝新手刷单视频教程 编辑:程序博客网 时间:2024/05/01 14:24

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2753
题目大意:一个人去滑雪,滑雪场由n个景点和m条边,他只会从一个景点滑到小于等于这个点高度的景点,他还有许多神奇的时间胶囊,用途是立即返回上一个景点,请问最多可以访问多少景点以及访问所有景点的最短路(时间胶囊可无限使用)

第一问直接BFS即可= =
手画一下第二问,会发现这其实是一个最小生成树……
但是题目里有限制:只能从高点跑到低点,正确解法是kruskal,开始建边时只建高->低的边,然后排序按照终点高度从低到高排序,相同的按边权从小到大排序……
然后最小生成树,要用到刚才BFS的结果:如果两个景点有任意一个不可以到达,就跳过,其他的和最小生成树完全一样= =
注意最后答案一定要开long long,否则WA哭……还有题目里的边数是200W,把边数组开大否则RE……

什么?求证明?我不会……(目测靠贪心思想证明)

#include <iostream>#include <cstdio>#include <algorithm>#include <queue>#define ll long longusing namespace std;struct Link{    int s,t,c,next;}l[5000000];int fa[200000];int h[200000];int g[200000];bool b[200000];queue<int> Q;int cnt = 0;int father(int x){    if(fa[x] != x)        fa[x] = father(fa[x]);    return fa[x];}bool cmp(Link a,Link b){    return h[b.t]<h[a.t]||((h[a.t]==h[b.t])&&(a.c<b.c));}void Add_Link(int s,int t,int c){    l[++cnt].s = s;    l[cnt].t = t;    l[cnt].c = c;    l[cnt].next = g[s];    g[s] = cnt;}int main(){    int n,m,s,t,c,ans = 0;    ll sum = 0;    scanf("%d%d",&n,&m);    for(int i = 1;i <= n;i ++)    {        scanf("%d",&h[i]);        fa[i] = i;    }    for(int i = 1;i <= m;i ++)    {        scanf("%d%d%d",&s,&t,&c);        if(h[t] >= h[s])            Add_Link(t,s,c);        if(h[t] <= h[s])            Add_Link(s,t,c);    }    b[1] = 1;    Q.push(1);    while(!Q.empty())    {        int x = Q.front();        ans ++;        Q.pop();        int w = g[x];        while(w)        {            if(!b[l[w].t])            {                b[l[w].t] = 1;                Q.push(l[w].t);            }            w = l[w].next;        }    }    cout << ans << " ";    sort(l+1,l+cnt+1,cmp);    for(int i = 1;i <= cnt;i ++)    {        int x = l[i].s;        int y = l[i].t;        if(!b[x] || !b[y])            continue ;        x = father(x);        y = father(y);        if(fa[x] != fa[y])        {            fa[x] = y;            sum += l[i].c;        }    }    cout << sum;    return 0;}
0 0
原创粉丝点击