P2323 [HNOI2006]公路修建问题
一道假的蓝题,真的假
讲道理我没看题解乱搞的就过了
一看就知道要二分答案啊。
初始化直接对所有的边排下序,贪心地取一号路,用并查集维护一下连通性就能建出生成树。我们要求的其实就是生成树。
方案因为有spj所以乱搞就可以了。我用vector再套pair,排一下第一维就可以了。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<utility>
#include<vector>
const int maxn = 10005, maxm = 20005;
struct edge
{
int u, v, c1, c2, id;
bool operator < (const edge &rhs) const
{
if(c1 == rhs.c1) return c2 < rhs.c2;
return c1 < rhs.c1;
}
} s[maxm];
int father[maxn];
int n, m, k;
std::vector<std::pair<int,int> > answer, temp;
int find(int x)
{
if(father[x] == x) return x;
return father[x] = find(father[x]);
}
void merge(int x, int y)
{
x = find(x); y = find(y);
if(x != y) father[x] = y;
}
bool check(int mid)
{
temp.clear();
for(int i = 1; i <= n; i++) father[i] = i;
int kk = 0, cnt = 0;
for(int i = 1; i < m; i++)
{
if(find(s[i].u) == find(s[i].v)) continue;
if(s[i].c1 <= mid)
{
kk++; cnt++;
merge(s[i].u, s[i].v);
temp.push_back(std::make_pair(s[i].id, 1));
}
else if(s[i].c2 <= mid)
{
cnt++;
merge(s[i].u, s[i].v);
temp.push_back(std::make_pair(s[i].id, 2));
}
}
if(cnt == n - 1 && kk >= k) return true;
return false;
}
int main()
{
scanf("%d%d%d", &n, &k, &m);
int left = 30005, right = -1, ans = -1;
for(int i = 1; i < m; i++)
{
scanf("%d%d%d%d", &s[i].u, &s[i].v, &s[i].c1, &s[i].c2);
s[i].id = i;
left = std::min(left, s[i].c2);
right = std::max(right, s[i].c1);
}
std::sort(s + 1, s + m);
while(left <= right)
{
int mid = (left + right) >> 1;
if(check(mid))
{
ans = mid, right = mid - 1;
answer = temp;
}
else left = mid + 1;
}
printf("%d\n", ans);
// ni de fang an
std::sort(answer.begin(), answer.end());
for(std::vector<std::pair<int,int> >::iterator it = answer.begin(); it != answer.end(); ++it)
{
printf("%d %d\n", it->first, it->second);
}
return 0;
}