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