【BZOJ】1601: [Usaco2008 Oct]灌水
2024-09-22 09:03:50
【算法】最小生成树
【题解】
想到网络流,但是好像不能处理流量和费用的关系。
想到最短路,但好像不能处理重复选边的问题。
每条边只需要选一次,每个点就要遍历到,可以想到最小生成树。
建超级源向每个点连边,点与点连边,对n+1个点求最小生成树(MST)即可。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=;
int n,first[maxn],tot,fa[maxn];
struct edge{int u,v,w,from;}e[maxn*maxn*];
void insert(int u,int v,int w)
{tot++;e[tot].u=u;e[tot].v=v;e[tot].w=w;e[tot].from=first[u];first[u]=tot;}
int getfa(int x){return fa[x]==x?x:(fa[x]=getfa(fa[x]));}
bool cmp(edge a,edge b)
{return a.w<b.w;}
int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
int u;
scanf("%d",&u);
insert(,i,u);
}
for(int i=;i<=n;i++)
{
for(int j=;j<=n;j++)
{
int u;
scanf("%d",&u);
insert(i,j,u);
}
}
for(int i=;i<=n;i++)fa[i]=i;
sort(e+,e+tot+,cmp);
int cnt=,ans=;
for(int i=;i<=tot;i++)
if(getfa(e[i].u)!=getfa(e[i].v))
{
cnt++;fa[fa[e[i].u]]=fa[e[i].v];
ans+=e[i].w;
if(cnt>=n)break;
}
printf("%d",ans);
return ;
}
最新文章
- Tomcat绑定IPV4端口
- animate对颜色设置不起作用
- 跟开涛老师学shiro -- INI配置
- 查询sql 并且读取
- poj3468 线段树+lazy标记
- Nutch的发展历程
- 开源:矿Android新闻client,快、小、支持离线阅读、操作简单、内容丰富,形式多样展示、的信息量、全功能 等待(离开码邮箱)
- [转载]关于shell脚本的基本语法
- tomcat bio nio apr 模式性能测试
- 使用xcrun打包iOS应用
- c#中@标志的作用
- neo4j-cypher
- Windows 10 IoT Core 17101 for Insider 版本更新
- 如何在Linux系统下挂载光盘
- 我的Java学习笔记-Java面向对象
- 为什么有时候访问某些加密https网站是不需要证书的? https? ssl?
- [SoapUI]怎样从应答报文中获取某个字段的值,然后用其改写某个变量
- 剑指offer(36-40)编程题
- Linux下IPC机制
- STL在算法比赛中简单应用