BZOJ 2654 & 玄学二分+MST
题意:
给一张图,边带权且带颜色黑白,求出一棵至少包含k条白边的MST
SOL:
正常人都想优先加黑边或者是白边,我也是这么想的...你看先用白边搞一棵k条边的MST...然后维护比较黑边跟白边像堆一样慢慢往里面加...不过讲课的时候跟原题有点出入...这里只有k条边好像比较难维护...
正解也非常巧妙...首先如果有一棵MST,他所含白边数量多于k,那么我们如果可以适当增加白边的边权那么我们就可以减少它的边而且达到最优....想想很有道理你让我证明那有点日了狗了...
然后我们就二分白边的增加值...然后一遍一遍地跑kruscal...多一个log...感觉还是很神...
反正我自己想我肯定想不出来...
Code:
/*================================================================= # Created time: 2016-03-30 19:36 # Filename: 2654.cpp # Description: =================================================================*/ #define me AcrossTheSky #include <cstdio> #include <cmath> #include <ctime> #include <string> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <vector> #define lowbit(x) (x)&(-x) #define FOR(i,a,b) for((i)=(a);(i)<=(b);(i)++) #define FORP(i,a,b) for(int i=(a);i<=(b);i++) #define FORM(i,a,b) for(int i=(a);i>=(b);i--) #define ls(a,b) (((a)+(b)) << 1) #define rs(a,b) (((a)+(b)) >> 1) #define getlc(a) ch[(a)][0] #define getrc(a) ch[(a)][1] #define maxn 1100 #define maxk 1010 #define maxm 100000 #define pi 3.1415926535898 #define _e 2.718281828459 #define INF 1070000000 using namespace std; typedef unsigned long long ull; template<class T> inline void read(T& num) { bool start=false,neg=false; char c; num=0; while((c=getchar())!=EOF) { if(c=='-') start=neg=true; else if(c>='0' && c<='9') { start=true; num=num*10+c-'0'; } else if(start) break; } if(neg) num=-num; } /*==================split line==================*/ struct edge{ int x,y,z,color; }e[100010]; struct bian{ int x,y,z,mrk; }a[100010]; inline bool operator<(const bian &a,const bian &b){ return a.z<b.z||a.z==b.z&&a.mrk>b.mrk; } int n,m,k,ans,tot,sum,tt; int fa[100010]; inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);} inline void judge(int mid) { tot=sum=0; FORP(i,1,n) fa[i]=i; FORP(i,1,m){ a[i].x=e[i].x; a[i].y=e[i].y; a[i].z=e[i].z+(e[i].color*mid); a[i].mrk=e[i].color; } sort(a+1,a+m+1); FORP(i,1,m){ int fx=find(a[i].x),fy=find(a[i].y); if (fx==fy)continue; if (a[i].mrk)tot++; fa[fx]=fy; sum+=a[i].z; } } int main(){ read(n); read(m); read(k); FORP(i,1,m){ read(e[i].x); e[i].x++; read(e[i].y); e[i].y++; read(e[i].z); read(e[i].color); e[i].color^=1; if (e[i].color)tt++; } int l=-105,r=105; while (l<=r){ int mid=(l+r)>>1; judge(mid); if (tot>=k){ans=sum-k*mid;l=mid+1;} else r=mid-1; } printf("%d\n",ans); return 0; }
Sometimes it s the very people who no one imagines anything of. who do the things that no one can imagine.