TZOJ 7034: 竹取飞翔 ~ Lunatic Princess 并查集+数学。

题目:

请添加图片描述

题解:

这道题比赛的时候没看,主要还是因为对集合求所有子集和不是很了解。
看了题解才知道 sum=(2^n-1)*(集合中数的和).。
然后就很简单了,用并查集维护祖孙节点就好了。
唯一的坑点就是原始的数据可能是负数,不能直接取模需要加上mod后取模。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int mod=1e9+7;
const int N=1e6+5;
int a[N],pre[N],cnt[N];
LL sum[N];
inline int read() 
{
    int f = 1;LL x = 0;char c = getchar();
    while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}
    while(c >= '0' && c <= '9'){x = (x<<1)+(x<<3)+(c^48);c = getchar();}
    return x*f;
}
LL ksm(LL a,int n)
{
	LL res=1;
	while(n)
	{
		if(n&1)res=res*a%mod;
		n=n>>1;
		a=a*a%mod; 
	}
	return res;
}
int findx(int x)
{
	return pre[x]==x?pre[x]:findx(pre[x]);
}
void merge(int x,int y)
{
	int tx=findx(x),ty=findx(y);
	if(tx==ty)return;
	else
	{
		pre[ty]=tx;
		sum[tx]=(sum[tx]+sum[ty])%mod;
		cnt[tx]+=cnt[ty];
	}
}
int main()
{
	int n,m;
	n=read(),m=read();
	for(int i=1;i<=n;i++)a[i]=read();
	for(int i=1;i<=n;i++)
	{
		pre[i]=i;
		sum[i]=(a[i]+mod)%mod;
		cnt[i]=1;
	}
	for(int i=1;i<=m;i++)
	{
		int k;
		k=read();
		if(k==1)
		{
			int x,y;
			x=read(),y=read();
			merge(x,y);
		}
		else if(k==2)
		{
			int x;
			int add;
			x=read(),add=read();;
			int tx=findx(x);
			sum[tx]=(sum[tx]+add+mod)%mod; 
		}
		else
		{
			int x;
			x=read();
			int tx=findx(x);
			printf("%lld\n",(ksm(2,cnt[tx]-1)*sum[tx])%mod);
		}
	}
} 

注意:最近tzoj跑的比较慢,建议使用快读优化。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值