您的位置:首页 > 其它

【BZOJ】4514: [Sdoi2016]数字配对

2017-02-27 08:48 267 查看
传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=4514

二分图带权匹配,跑费用流到匹配费用小于0时停止

#include<stdio.h>
#include<algorithm>
#include<queue>
#include<cmath>
#define V e[i].v
#define C e[i].c
#define F e[i].f
#define cint const int &
#define Bool inline bool
#define inf 233333333
#define N 207
using namespace std;
typedef long long ll;
struct edge{int v,c,n;ll f;}e[(N*N<<1)+(N<<2)];
queue<int> Q;
int a
,b
,c
,tot=1,s
,ts,tm
,mc
,fm
,fe
,n,S,E,ans,col
;
ll dis
,mx;
bool vis
,mp

;

Bool pri(cint k)
{
int lim=sqrt(k);
for (int i=2;i<=lim;i++) if (k % i==0) return 0;
return 1<k;
}

inline void push(cint u,cint v,cint c,const ll &f){e[++tot]=(edge){v,c,s[u],f};s[u]=tot;}

Bool bfs()
{
Q.push(S);vis[S]=1;tm[S]=++ts;mc[S]=inf;
while (!Q.empty())
{
int h=Q.front(),c=mc[h];Q.pop();ll f=dis[h];vis[h]=0;
for (int i=s[h];i;i=e[i].n)
if (C && (tm[V]!=ts || dis[V]<f+F || (dis[V]==f+F && mc[V]<min(C,c))))
{
dis[V]=f+F;mc[V]=min(C,c);fm[V]=h;fe[V]=i;tm[V]=ts;
if (!vis[V]) Q.push(V),vis[V]=1;
}
}
if (tm[E]==ts && 0<=mx+dis[E])
{
int flow=0;
if (0<=dis[E]) mx+=dis[E]*mc[E],flow=mc[E];
else flow=min(-mx/dis[E],(ll)mc[E]),mx+=dis[E]*flow;
for (int i=E;i!=S;i=fm[i]) e[fe[i]].c-=flow,e[fe[i]^1].c+=flow;
ans+=flow;
return 1;
}
return 0;
}

void dfs(cint k)
{
if (col[k]==1) push(S,k,b[k],0),push(k,S,0,0);
else push(k,E,b[k],0),push(E,k,0,0);
for (int i=1;i<=n;i++) if ((!col[i]) && mp[k][i]) col[i]=col[k]^3,dfs(i);
}

int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",a+i);
for (int i=1;i<=n;i++) scanf("%d",b+i);
for (int i=1;i<=n;i++) scanf("%d",c+i);
for (int i=1;i<=n;i++) for (int j=1;j<=n;j++)
if (i!=j && a[i] % a[j]==0 && pri(a[i]/a[j])) mp[i][j]=mp[j][i]=1;
S=n+1,E=n+2;
for (int i=1;i<=n;i++) if (!col[i]) col[i]=1,dfs(i);
for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++) if (mp[i][j])
{
if (col[i]==1) push(i,j,inf,(ll)c[i]*c[j]),push(j,i,0,-(ll)c[i]*c[j]);
else push(j,i,inf,(ll)c[i]*c[j]),push(i,j,0,-(ll)c[i]*c[j]);
}
while (bfs());
printf("%d",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: