codeforces 959E

Mahmoud and Ehab and the xor-MST

题意:给一个n个点的完全图,每条边的边权为2点的编号异或值(编号0~n-1),求最小生成树

思路:打表找规律

AC代码:

#include "iostream"
#include "iomanip"
#include "string.h"
#include "stack"
#include "queue"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "algorithm"
#include "stdio.h"
#include "math.h"
#pragma comment(linker, "/STACK:102400000,102400000")
#define bug(x) cout<<x<<" "<<"UUUUU"<<endl;
#define mem(a,x) memset(a,x,sizeof(a))
#define step(x) fixed<< setprecision(x)<<
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define ll long long
#define endl ("\n")
#define ft first
#define sd second
#define lrt (rt<<1)
#define rrt (rt<<1|1)
using namespace std;
const ll mod=1e9+7;
const ll INF = 1e18+1LL;
const int inf = 1e9+1e8;
const double PI=acos(-1.0);
const int N=1e5+100;

ll b[10] = {0,1,3,4,8,9,11,12};
ll f(ll x){
    if(x < 6) return b[x];
    if(x&1) return 2*f(x/2)+x/2+1;
    else return 2*f(x/2)+x/2;
}
int main() {
    ll n; scanf("%lld", &n);
    printf("%lld", f(n-1));
    return 0;
}

打表代码:

#include "iostream"
#include "iomanip"
#include "string.h"
#include "stack"
#include "queue"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "algorithm"
#include "stdio.h"
#include "math.h"
#pragma comment(linker, "/STACK:102400000,102400000")
#define bug(x) cout<<x<<" "<<"UUUUU"<<endl;
#define mem(a,x) memset(a,x,sizeof(a))
#define step(x) fixed<< setprecision(x)<<
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define ll long long
#define endl ("\n")
#define ft first
#define sd second
#define lrt (rt<<1)
#define rrt (rt<<1|1)
using namespace std;
const ll mod=1e9+7;
const ll INF = 1e18+1LL;
const int inf = 1e9+1e8;
const double PI=acos(-1.0);
const int N=1e5+100;

struct Edge {
    int u, v;
    int w;
    bool friend operator< (Edge a, Edge b) {
        return a.w<b.w;
    }
};
Edge e[1000005];
int n, cnt, fa[1000005];

int finds(int x) {
    return fa[x]=(fa[x]==x?x:finds(fa[x]));
}

void unions(int x, int y) {
    int fx = finds(x), fy = finds(y);
    fa[fx] = fy;
}

int kruscal() {
    sort(e+1, e+1+cnt);
    int k = 0, ret = 0;
    for(int t=1; t<=cnt; ++t) {
         int fu = finds(e[t].u), fv = finds(e[t].v);
         if(fu != fv) { //cout<<e[t].u<<" uu "<<e[t].v<<endl;
            unions(fu, fv);
            ret += e[t].w;
         }
    }
    return ret;
}

int main() {

    for(n=1; n<100; ++n) {//if(n!=4) continue;
        cnt = 0;
        mem(e, 0);
        for(int i=0; i<n; ++i) {
            for(int j=i+1; j<n; ++j) {
                e[++cnt].u = i;
                e[cnt].v = j;
                e[cnt].w = i^j;
            }
        }
        for(int i=0; i<=n; ++i) fa[i] = i;
        printf("%d %d\n", n, kruscal());
    }
    return 0;
}

 

posted on 2018-04-17 17:11  lazzzy  阅读(132)  评论(0编辑  收藏  举报

导航