洛谷P2323 [HNOI2006]公路修建问题
https://www.luogu.org/problem/show?pid=2323
题目描述
输入输出格式
输入格式:
在实际评测时,将只会有m-1行公路
输出格式:
输入输出样例
输入样例#1:
4 2 5 1 2 6 5 1 3 3 1 2 3 9 4 2 4 6 1 3 4 4 2
输出样例#1:
4 2 1 3 2 5 1
输入样例#2:
4 1 5 1 2 6 5 1 3 3 1 2 3 9 4 2 4 6 1 3 4 4 3
输出样例#2:
3 2 1 4 2 5 2
#include<bits/stdc++.h> using namespace std; #define maxn 10000000 int n,m,k,ans,fa[maxn],x[maxn],y[maxn]; struct Edge { int x,y,c1,c2; bool p1,p2; }edge[maxn]; int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);} bool cmp(Edge a,Edge b){return a.c1<b.c1;} bool cmp2(Edge a,Edge b){return a.c2<b.c2;} bool work(int x) { int cnt=0; for(int i=1;i<=n;i++) fa[i]=i; for(int i=1;i<=m;i++) { edge[i].p1=false; if(edge[i].c1>x) continue ; int fx=find(edge[i].x); int fy=find(edge[i].y); if(fx!=fy) { cnt++; fa[fx]=fy; edge[i].p1=true; } } if(cnt<k) return false; for(int i=1;i<=m;i++) { edge[i].p2=false; if(edge[i].c2>x) continue ; int fx=find(edge[i].x); int fy=find(edge[i].y); if(fx!=fy) { cnt++; fa[fx]=fy; edge[i].p2=true; } } if(cnt!=n-1) return false ; return true; } int main() { scanf("%d%d%d",&n,&k,&m); for(int i=1;i<=m;i++) scanf("%d%d%d%d",&edge[i].x,&edge[i].y,&edge[i].c1,&edge[i].c2); //sort(edge+1,edge+m+1,cmp); //sort(edge+1+k,edge+m+1,cmp2); int l=0,r=100000; while(l<=r) { int mid=(l+r)>>1; if(work(mid)) { r=mid-1; ans=mid; } else l=mid+1; } work(ans); printf("%d\n",ans); for(int i=1;i<=m;i++) { if(edge[i].p1) printf("%d %d\n",i,1); if(edge[i].p2) printf("%d %d\n",i,2); } return 0; }