pat-top 1013. Image Segmentation (35)

9 篇文章 0 订阅
5 篇文章 0 订阅

https://www.patest.cn/contests/pat-t-practise/1013

这道题自己的想法是 算出一个个mst,然后看每个MST的最长边是否可以分解。 但是没想出好的dfs模型


后来看了http://blog.csdn.net/jtjy568805874/article/details/53435235,逆向思维,从搭建compoent的角度出发。去填边,正是堆+并查集求MST的思路,很精彩。


code from http://blog.csdn.net/jtjy568805874/article/details/53435235

#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;

#define rep(i,j,k) for(int i=j;i<=k;i++)
#define inthr(x,y,z) scanf("%d%d%lf",&x,&y,&z)
const int maxn = 8e3 + 10;

int n, m;
int fa[maxn], c[maxn]; //fa:father;  nodes count of component
double C, mw[maxn]; //mw:max edge weight;
vector<int> res[maxn];// restore the components

typedef struct edge {
	int x, y; double w;
	bool friend operator < (struct edge a, struct edge b) {
		return a.w < b.w;
	}
}Edge;
Edge edges[maxn];


int find(int x) {
	if (x == fa[x]) return x;
	fa[x] = find(fa[x]);
	c[fa[x]] += c[x]; c[x] = 0; //merge the nodes count
	return fa[x];
}

int cmp(vector<int> a,vector<int> b) {
	if (!a.size() && b.size()) return true;
	if (!b.size()) return false;
	return a[0] < b[0];
}

int main()
{
	inthr(n, m, C);
	rep(i, 0, n - 1) fa[i] = i, mw[i] = 0, c[i] = 1;
	rep(i, 0, m - 1) inthr(edges[i].x, edges[i].y, edges[i].w);
	sort(edges, edges + m);
	rep(i, 0, m - 1) 
	{
		int fx = find(edges[i].x), fy = find(edges[i].y);
		if (fx == fy) continue;
		if (fx > fy) swap(fx, fy);
		if (mw[fx] + C / c[fx] < edges[i].w) continue;
		if (mw[fy] + C / c[fy] < edges[i].w) continue;
		fa[fy] = fx; find(fy); mw[fx] = edges[i].w;
	}
	rep(i, 0, n - 1) res[find(i)].push_back(i);
	rep(i, 0, n - 1) sort(res[i].begin(), res[i].end());
	sort(res, res + n, cmp);
	rep(i, 0, n - 1)
	{
		if (res[i].size())
		{
			rep(j, 0, res[i].size() - 1)
			{
				printf("%s%d",j==0?"":" ",res[i][j]);
			}
			printf("\n");
		}
	}
	return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值