F - Minimal Spanning Tree HDU - 4896

Given a connected, undirected, weight graph G, your task is to select a subset of edges so that after deleting all the other edges, the graph G is still connected. If there are multiple ways to do this, you should choose the way that minimize the sum of the weight of these selected edges.

Please note that the graph G might be very large. we'll give you two numbers: N, and seed, N is number of nodes in graph G, the following psuedo-code shows how to to generate graph G.



Here ♁ represents bitwise xor (exclusive-or).

Input

Input contains several test cases, please process till EOF.
For each test case, the only line contains two numbers: N and seed.(1 ≤ N ≤ 10000000, 1 ≤ seed ≤ 2333332)

Output

For each test case output one number, the minimal sum of weight of the edges you selected.

Sample Input

6 2877
2 17886
3 22452

Sample Output

2157810
259637
1352144
#include<iostream>
#include<algorithm>
using namespace std;
typedef int ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 10000010*5;
const int mode =2333333;

int father[MAXN];
int level[MAXN];

void init(int n){
    for(int i=1;i<=n;i++){
        father[i]= i;
        level[i] = 0;
    }
}


int getfather(int n){

    if(father[n]==n){
        return n;
    }else{
        return father[n] = getfather(father[n]);

    }

}

bool same(int x,int y){
    x = getfather(x);
    y = getfather(y);
    if(x==y){
        return true;
    }
    return false;

}

void combine(int x,int y){
    if(same(x,y)){
        return;
    }

    if(level[x]>level[y]){
        father[y]=x;
    }else{
        father[x] =y;
        if(level[x]==level[y]){
            level[y]++;
        }
    }
}
struct node{
    ll start,end,weight;
};

bool cmp(const node &a,const node &b){
    return a.weight<b.weight;
}

node edge[MAXN];

int main(){

    int N;
    int seed;

    while(scanf("%d",&N)!=EOF){
        scanf("%d",&seed);

        ll x = seed;
        ll id = 0;
        //get weight
        for(int i=2;i<=N;i++){

            x = x*907%2333333;
            ll T = x;

            for(int j=max(1,i-5);j<=i-1;j++){
                x = x*907%2333333;
                ll w = x^T;

                edge[id].start = j;
                edge[id].end = i;
                edge[id].weight = w;
                id++;
            }
        }

        init(N);
        sort(edge,edge+id,cmp);

        ll res =0;
        for(int i=0;i<id;i++){

            if(!same(edge[i].start,edge[i].end)){
                res += edge[i].weight;
                combine(edge[i].start,edge[i].end);
            }
        }

        printf("%lld\n",res);

    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Willen_/article/details/85271882