Codeforces_959D_E. Mahmoud and Ehab and the xor-MST

版权声明: https://blog.csdn.net/yyy_3y/article/details/79965652

传送门
思路:很有趣的题目,比赛的时候一直找规律,想着可以晚点再打表,结果GG。
其实对于一个数字,它连接的点一定是lowbit(x),这样就是满足边的权值最小。
所以:这道题最后的规律就是统计1的数量。
打表:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<fstream>
using namespace std;

const int MAXN=505;//最大点数
const int MAXM=250005;//最大边数
int F[MAXN];//并查集使用

struct Edge
{
    int u,v,w;
}edge[MAXM];//储存边的信息,包括起点/终点/权值

int tol;//边数,加边前赋值为0

void addedge(int u,int v,int w)
{
    edge[tol].u=u;
    edge[tol].v=v;
    edge[tol++].w=w;
}

bool cmp(Edge a,Edge b)//排序函数,边按照权值从小到大排序
{
    return a.w<b.w;
}

int Find(int x)
{
    if(F[x]==-1)
        return x;
    else
        return F[x]=Find(F[x]);
}

int Kruskal(int n)//传入点数,返回最小生成树的权值,如果不连通返回-1
{
    memset(F,-1,sizeof(F));
    sort(edge,edge+tol,cmp);
    int cnt=0;//计算加入的边数
    int ans=0;
    for(int i=0;i<tol;i++)
    {
        int u=edge[i].u;
        int v=edge[i].v;
        int w=edge[i].w;
        int t1=Find(u);
        int t2=Find(v);
        if(t1!=t2)
        {
            ans+=w;
            F[t1]=t2;
            cnt++;
        }
        if(cnt==n-1)
            break;
    }
    if(cnt<n-1)
        return -1;//不连通
    else
        return ans;
}

int main()
{
    for(int n=2;n<=100;n++)
    {
        tol=0;
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                addedge(i,j,i^j);
                addedge(j,i,i^j);
            }
        }
        cout<<n<<"="<<Kruskal(n)<<endl;
    }
    return 0;
}

#include<bits/stdc++.h>
#define debug(a) cout << #a << " " << a << endl
#define LL long long
#define ull unsigned long long
#define PI acos(-1.0)
#define eps 1e-6
const int N=1e5+7;
using namespace std;
LL solve(LL x)
{
    if(x==0) return 0;
    return 2ll*solve(x>>1)+(x+1)/2;
}
int main ()
{
    //yyy_3y
    //freopen("1.in","r",stdin);
    LL n; scanf("%lld",&n);
    printf("%lld\n",solve(n-1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yyy_3y/article/details/79965652