幸運樹 51Nod - 1588

https://www.51nod.com/Challenge/Problem.html#!#problemId=1588

用並查集維護非幸運邊構成的連通塊大小cnt[i] 然後用幸運邊建圖

枚舉每個連通塊 算以該連通塊中的點爲中點(即三元組中的i)時有多少可能 剩下的兩個點(即三元組中的jk)從n-cnt[i]中任選兩個 因爲有順序 乘二即可

 

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;

struct node1
{
    int u,v,tp;
};

struct node2
{
    int v,next;
};

node1 pre[maxn];
node2 edge[2*maxn];
int first[maxn],f[maxn],cnt[maxn],mp[maxn];
ll ans;
int n,num;

bool judge(int val)
{
    while(val>0){
        if(val%10!=4&&val%10!=7) return 0;
        val/=10;
    }
    return 1;
}

int getf(int p)
{
    if(f[p]==p) return p;
    else return f[p]=getf(f[p]);
}

void unite(int u,int v)
{
    int fu,fv;
    fu=getf(u),fv=getf(v);
    if(fu!=fv){
        f[fv]=fu;
        cnt[fu]+=cnt[fv];
    }
}

void addedge(int u,int v)
{
    edge[num].v=v;
    edge[num].next=first[u];
    first[u]=num++;
}

void dfs(int cur,int fa)
{
    ll a,b,c;
    int i,v;
    a=cnt[cur],b=n-cnt[cur],c=n-cnt[cur]-1;
    ans+=a*b*c;
    for(i=first[cur];i!=-1;i=edge[i].next){
        v=edge[i].v;
        if(v!=fa){
            dfs(v,cur);
        }
    }
}

int main()
{
    ll a,b;
    int i;
    scanf("%d",&n);
    for(i=1;i<=n-1;i++){
        scanf("%d%d%d",&pre[i].u,&pre[i].v,&pre[i].tp);
        pre[i].tp=judge(pre[i].tp);
    }

    for(i=1;i<=n;i++){
        f[i]=i,cnt[i]=1;
    }
    for(i=1;i<=n-1;i++){
        if(pre[i].tp==0){
            unite(pre[i].u,pre[i].v);
        }
    }
    for(i=1;i<=n;i++){
        mp[i]=getf(i);
    }

    memset(first,-1,sizeof(first));
    num=0;
    for(i=1;i<=n-1;i++){
        if(pre[i].tp==1){
            addedge(mp[pre[i].u],mp[pre[i].v]);
            addedge(mp[pre[i].v],mp[pre[i].u]);
        }
    }
    dfs(mp[1],0);
    printf("%lld\n",ans);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章