tyvj 2054 [Nescafé29]四叶草魔杖【克鲁斯卡尔+状压dp】
2024-09-07 17:12:27
传送:http://www.joyoi.cn/problem/tyvj-2054
来自lyd课件:
所以先预处理出各个sum为0的块,然后状压dfs取min来得到答案
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=100005,inf=1e9;
int n,m,a[N],c[N],w[N],fa[N],f[N],tot;
bool v[N];
struct qwe
{
int u,v,w;
}e[N];
bool cmp(const qwe &a,const qwe &b)
{
return a.w<b.w;
}
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
int zhao(int x)
{
return fa[x]==x?x:fa[x]=zhao(fa[x]);
}
void wk(int s)
{
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=m;i++)
if((s&(1<<(e[i].u-1)))&&(s&(1<<(e[i].v-1))))
{
int fu=zhao(e[i].u),fv=zhao(e[i].v);
if(fu!=fv)
{
fa[fu]=fv;
c[tot]+=e[i].w;
}
}
int rt=0;
for(int i=1;i<=n;i++)
if(s&(1<<(i-1)))
{
if(rt==0)
rt=zhao(i);
else if(zhao(i)!=rt)
{
v[tot]=c[tot]=0;
tot--;
return;
}
}
}
void dfs(int s)
{//cerr<<s<<endl;
if(v[s])
return;
v[s]=1;
for(int i=1;i<=tot;i++)
if((s&w[i])==w[i])
{
dfs(s-w[i]);
f[s]=min(f[s],f[s-w[i]]+c[i]);
}
}
int main()
{
n=read(),m=read();
for(int i=1;i<=n;i++)
a[i]=read();
for(int i=1;i<=m;i++)
e[i].u=read()+1,e[i].v=read()+1,e[i].w=read();
sort(e+1,e+1+m,cmp);
for(int i=1;i<(1<<n);i++)
{
int sum=0;
for(int j=1;j<=n;j++)
if(i&(1<<(j-1)))
sum+=a[j];
if(sum)
continue;
w[++tot]=i;
wk(i);
}
for(int i=1;i<=(1<<n);i++)
f[i]=1e9;
dfs((1<<n)-1);
if(f[(1<<n)-1]==1e9)
puts("Impossible");
else
printf("%d\n",f[(1<<n)-1]);
return 0;
}
最新文章
- Daily Scrum Meeting ——EighthDay
- php时间设置为本地
- poj 2513 Colored Sticks trie树+欧拉图+并查集
- 面向对象编程(八)——this关键字
- React + Reflux
- Nuttx操作系统
- PHP 文字,图片水印,缩略图,裁切成小图(大小变小)
- Eclipse Python配置
- NOI十连测 第四测 T2
- Android应用程序窗口(Activity)的测量(Measure)、布局(Layout)和绘制(Draw)过程分析
- WCF方式调用asmx设置cookie
- 用 Asterisk 搭建自己的免费 VoIP 服务器
- Redux管理你的React应用
- 论文阅读 | CrystalBall: A Visual Analytic System for Future Event Discovery and Analysis from Social Media Data
- 数据仓库系列 - 缓慢渐变维度 (Slowly Changing Dimension) 常见的三种类型及原型设计
- 【爬坑】远程连接 MySQL 失败
- 自学Python之路-Python核心编程
- html 文档类型
- Ngnix + Tomcat负载均衡架构
- gentoo moc audacious