把博客园图标替换成自己的图标
把博客园图标替换成自己的图标end

luogu P2065 [TJOI2011]卡片

题面传送门
一眼就是二分图,但是考虑怎么建边。
如果暴力匹配\(O(nmtlogw)\)肯定会\(T\)飞。
卡片上的数的阈值范围很小,可以考虑欧拉筛一趟然后分解质因数。
分解质因数后对于每个质数开一个邻接表,然后对于每一个建边。
建边复杂度就变成了\(O(tnlogw)\)
代码实现:

#include<cstdio>
#include<cstring>
#include<queue>
#define min(a,b) ((a)<(b)?(a):(b))
using namespace std;
int n,m,k,T,x,y,z,pr[670039],now[1039],d[1039],f[10000039],nows,ph,last[10000039],a[1039],b[1039],tots,pus,cur,st,t,ans;
struct yyy{int to,w,z;}tmp;
struct ljb{
	int head,h[670039];
	yyy f[670039];
	inline void add(int x,int y,int z){
		f[head]=(yyy){y,z,h[x]};
		h[x]=head++;
	}
}s,c;
queue<int > q;
inline int bfs(){
	while(!q.empty()) q.pop();
	memset(d,0x3f,sizeof(d));
	d[st]=0;
	q.push(st);
	now[st]=s.h[st];
	while(!q.empty()){
		nows=q.front();
		q.pop();
		cur=s.h[nows];
		while(cur!=-1){
			tmp=s.f[cur];
			if(tmp.w&&d[tmp.to]>=1e9){
				now[tmp.to]=s.h[tmp.to];d[tmp.to]=d[nows]+1;q.push(tmp.to);
				if(tmp.to==t) return 1;
			}
			cur=tmp.z;
		}
	}
	return 0;
}
inline int dfs(int x,int sum){
	if(x==t) return sum;
	int cur=now[x],k,pus=0;
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		now[x]=cur;
		if(d[tmp.to]==d[x]+1&&tmp.w){
			k=dfs(tmp.to,min(tmp.w,sum));
			if(!k)d[tmp.to]=1e9;
			s.f[cur].w-=k;
			s.f[cur^1].w+=k;
			pus+=k;
			sum-=k;
		}
		if(!sum) break;
		cur=tmp.z;
	}
	return pus;
}
int main(){
	register int i,j;
	for(i=2;i<=1e7;i++) {
		if(!f[i]) pr[++ph]=i,last[i]=ph;
		for(j=1;j<=ph&&i*pr[j]<=1e7;j++){
			f[i*pr[j]]=1;
			last[i*pr[j]]=j;
			if(i%pr[j]==0) break;
		}
	}
	scanf("%d",&T);
	while(T--){
		memset(s.h,-1,sizeof(s.h));
		memset(c.h,-1,sizeof(c.h));
		s.head=c.head=ans=0;
		scanf("%d%d",&n,&m);
		for(i=1;i<=n;i++)scanf("%d",&a[i]);
		for(i=1;i<=m;i++) scanf("%d",&b[i]);
		for(i=1;i<=m;i++){
			tots=b[i];
			while(tots!=1){
				c.add(last[tots],i,1);
				tots/=pr[last[tots]];
			}
		}
		for(i=1;i<=n;i++){
			tots=a[i];
			while(tots!=1){
				cur=c.h[last[tots]];
				while(cur!=-1){
					tmp=c.f[cur];
					s.add(i,tmp.to+n,1);s.add(tmp.to+n,i,0);
					cur=tmp.z;
				}
				tots/=pr[last[tots]];
			}
		}
		st=0;t=n+m+1;
		for(i=1;i<=n;i++)s.add(0,i,1),s.add(i,0,0);
		for(i=1;i<=m;i++)s.add(i+n,t,1),s.add(t,i+n,0);
		while(bfs()) ans+=dfs(st,1e8);
		printf("%d\n",ans);
	}
}
posted @ 2020-08-22 13:56  275307894a  阅读(50)  评论(0)    收藏  举报
浏览器标题切换
浏览器标题切换end