Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) G

题意:

给定一棵树,每条边有权,定义三元组(u,v,s)为存在一条从u到v的路径,路径xor值为s,且u <= v,问所有这样的三元组的s之和是多少??


solution:

一条从u到v的路径,总是可以通过任取一条路,xor连通块内的环搞出。随意取出一个连通块处理,先dfs出一棵dfs树,那么一条非树边对应一个环,把环的权值拿去组成一个线性空间,高斯消元求出线性基(今天才发现之前自己写的求基是错的。。。),假设得到的是r维线性空间

那么对于(u,v,s),不同的s有2^r种,通过基xor出来就是。对于dfs中的每个节点,处理出它到根的路径的xor

记这些xor值中第i位是0的有ai个,第i位是1的有bi个

对于第k位,如果任意一个基的第k位是1,那么贡献2^k*C(n,2)*2^(r-1),因为你总能通过基xor出这一位的1

否则贡献是ak*bk*2^k*2^r,因为这时候就要靠原路径xor出来了

#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<bitset>
#include<algorithm>
#include<cstring>
#include<map>
#include<stack>
#include<set>
#include<cmath>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;

const int maxn = 1E5 + 10;
typedef long long LL;
LL mo = 1E9 + 7;

struct E{
	int to; LL va;
	E(){}
	E(int to,LL va): to(to),va(va){}
};

int n,m,tot,L[maxn];
LL t,f[2][66],ans,w[maxn],A[2*maxn],B[66];
bool C[66];

vector <E> v[maxn];

void Dfs(int x,int fa)
{
	++t; LL y = w[x];
	for (int i = 0; i <= 60; i++,y >>= 1LL)
		++f[y&1LL][i];
	for (int i = 0; i < v[x].size(); i++) {
		int to = v[x][i].to;
		if (to == fa) continue;
		if (L[to]) {
			if (L[x] >= L[to])
				A[++tot] = (w[x]^w[to]^v[x][i].va);
			continue;
		}
		L[to] = L[x] + 1;
		w[to] = (w[x]^v[x][i].va);
		Dfs(to,x);
	}
}

bool cmp(const LL &x,const LL &y) {return x > y;}
void Solve(int x)
{
	memset(f,0,sizeof(f));
	tot = t = 0;
	L[x] = 1;
	Dfs(x,0);
	memset(B,0,sizeof(B));
	memset(C,0,sizeof(C));
	LL cnt = 0;
	for (LL j = 60; j >= 0; j--)
		for (int i = 1; i <= tot; i++)
			if ((A[i] >> j) == 1) {
				if (!B[j]) B[j] = A[i];
				else A[i] ^= B[j];
			}
	for (int j = 60; j >= 0; j--)
		if (B[j]) ++cnt;
	for (int i = 1; i <= tot; i++)
		for (LL j = 60; j >= 0; j--)
			if ((A[i] >> j) & 1)
				C[j] = 1;
	t = t*(t-1LL)/2LL%mo;
	LL a = (1LL<<(cnt-1))%mo;
	LL b = (1LL<<cnt)%mo;
	LL now = 1;
	for (int j = 0; j <= 60; j++) {
		if (C[j]) {
			ans += t*now%mo*a%mo;
			ans %= mo;
		}
		else {
			ans += f[0][j]*f[1][j]%mo*now%mo*b%mo;
			ans %= mo;
		}
		now <<= 1LL;
		now %= mo;
	}
}

int main()
{
	#ifdef DMC
		freopen("DMC.txt","r",stdin);
	#endif
	
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x,y; LL w;
		scanf("%d%d%I64d",&x,&y,&w);
		v[x].push_back(E(y,w));
		v[y].push_back(E(x,w));
	}
	for (int i = 1; i <= n; i++)
		if (!L[i]) Solve(i);
	cout << ans;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值