[2019CCPC哈尔滨] E Exchanging Gifts 拓扑排序

给出 n ≤ 1 e 6 n\leq1e6 n1e6个数字串,数字串的总和不会超过 1 e 6 1e6 1e6,但是会有一个将两个数字串连接的操作,总数字串的长度会比较大,最大会有 1 e 18 1e18 1e18。然后求问你可以通过若干次交换,使得最多的数字自己的位置上和原来的数字不同,求这个最大值。
可以发现不同的数字不会超过 1 e 6 1e6 1e6个,所以可以考虑基于值然后统计每个值的次数。对于每个被生成的串,由它向合成它的两个串连一条有向边,然后从最后一个串开始 B F S BFS BFS找到有效的那一部分子图。然后对这张图拓扑可以得到每个串被使用的次数,然后就容易统计每个数出现的次数了。
如果出现次数最多的那个数大于等于剩下的所有数的和,那么答案就是剩下数的和的两倍,否则都可以错位。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int N=1e6+7;
inline char nc() {
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
template <typename _Tp> inline void read(_Tp&sum) {
	char ch=nc();sum=0;
	while(!(ch>='0'&&ch<='9')) ch=nc();
	while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();
}
map<int,ll> mp; 
vector<int> a[N];
vector<int> go[N];
int in[N];
ll cnt[N]; 
bool vis[N];
void bfs(int s) {
	queue<int> q;
	q.push(s);
	vis[s]=1;
	while(!q.empty()) {
		int u=q.front();
		q.pop();
		for(auto &v:go[u]) {
			in[v]++;
			if(!vis[v]) {
				vis[v]=1;
				q.push(v);
			}
		}
	}
} 
void topo(int s) {
	queue<int> q;
	q.push(s);
	cnt[s]=1;
	while(!q.empty()) {
		int u=q.front();
		q.pop();
		if(go[u].size()==0) {
			for(auto &x:a[u]) { 
				mp[x]+=cnt[u];
			}
		}
		for(auto &v:go[u]) {
			cnt[v]+=cnt[u];
			if((--in[v])==0) q.push(v);
		}
	}
}
int main() {
	int T;
	read(T);
	while(T--) {
		int n;
		read(n);
		for(int i=1;i<=n;i++) {
			a[i].clear();
			go[i].clear();
			vis[i]=0; 
			in[i]=0;
			cnt[i]=0;
			mp.clear(); 
		}
		for(int i=1;i<=n;i++) {
			int opt,k,x,y;
			read(opt); 
			if(opt==1) {
				read(k);
				for(int j=1;j<=k;j++) {
					read(x); 
					a[i].emplace_back(x);
				}	
			}
			else {
				read(x);read(y); 
				go[i].emplace_back(x);
				go[i].emplace_back(y);
			}
		}
		bfs(n); 
		topo(n);
		ll sum=0,mx=0;
		for(auto &x:mp) {
			mx=max(mx,x.second);
			sum+=x.second;
		}
		if(mx>=sum-mx) printf("%lld\n",2ll*(sum-mx));
		else printf("%lld\n",sum); 
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值