题目链接:hdu4786
题意:给你一个图,判断是否存在一个生成树,使得权值之和为一个斐波那契数。
思路:分别跑一次最大生成树和最小生成树。然后判断两个生成树的权值中间是否存在一个斐波那契数。如果存在则输出yes,否则输出no
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
struct node {
int from, to, w;
node(int a, int b, int c) :from(a), to(b), w(c) {}
};
int vex[maxn];
int n, m;
int fib[maxn];
vector<node> v;
void fibs() {
int i;
fib[0] = 1;
fib[1] = 1;
for (i = 2; i < 100000; i++)
fib[i] = fib[i - 1] + fib[i - 2];
}
void init() {
int i;
for (i = 0; i <= n; i++) {
vex[i] = i;
}
}
int find(int x)
{
if (vex[x] == x)
return x;
return vex[x] = find(vex[x]);
}
void kruskal(int &cnt) {
int i;
int a, b;
for (i = 0; i < m; i++) {
auto e = v[i];
a = e.from;
b = e.to;
int r1 = find(a);
int r2 = find(b);
if (r1 != r2) {
vex[r1] = r2;
cnt += e.w;
}
}
}
int main() {
ios::sync_with_stdio(false);
fibs();
int t;
cin >> t;
int cases = 0;
while (t--) {
v.clear();
cases++;
cin >> n >> m;
int a, b, w, i;
for (i = 0; i < m; i++) {
cin >> a >> b >> w;
v.push_back(node(a, b, w));
}
sort(v.begin(), v.end(), [=](node n1, node n2)
{
return n1.w > n2.w;
});
memset(vex, 0, sizeof(vex));
int flag = 0;
int maxs, mins;
maxs = mins = 0;
init();
kruskal(maxs);
memset(vex, 0, sizeof(vex));
sort(v.begin(), v.end(), [=](node n1, node n2)
{
return n1.w < n2.w;
});
init();
kruskal(mins);
int cnts = 0;
for (i = 0; maxs >= fib[i]; i++) {
if (mins <= fib[i] && maxs >= fib[i]) {
flag = 1;
break;
}
}
for (i = 1; i <= n; i++) {
if (vex[i] == i)
cnts++;
if (cnts > 1)
break;
}
if (cnts > 1)
flag = 0;
cout << "Case #" << cases << ": ";
if (flag)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
jiangxiaoju
发布了34 篇原创文章 · 获赞 44 · 访问量 3万+
私信
关注