pat-top 1013. Image Segmentation (35)

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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章