纪念我常数巨大的做法。
这题 的数据范围,不两个log可惜了…充分利用条件。
很容易想到二分答案,之后转化为判定问题。
正着做有点困难,由https://www.luogu.com.cn/problem/CF1500C这题受到启发,想到倒着来做。于是问题变成能否选一个点,使得它所在的联通块能够不断加入新的点,条件是当前二分的值加点权总和减去连通块点权和小于等于边权。
我又想到了一个奇怪的做法,就是维护连通块的点权和,每次把最小的点权和当作连通块权值,看能否加入新的边,如果不能就把这个连通块删掉,换更大的点权和。被删掉的连通块可以认为是“孤立的”,要等待其他点来连它,但是两个被删掉的也可以连起来,不会影响。
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
int Read()
{
char c=getchar();
while (c<'0'||c>'9') c=getchar();
int t=c-'0'; c=getchar();
while (c>='0'&&c<='9') t=(t<<3)+(t<<1)+c-'0',c=getchar();
return t;
}
int n,m;
long long c[100001],sum;
struct Node
{
int a,b;
long long w;
}s[100001],tem[100001];
bool cmp(const Node& t1,const Node& t2)
{
return t1.w>t2.w;
}
int f[100001];
int Find(int k)
{
if (f[k]==k) return k;
else return f[k]=Find(f[k]);
}
long long w[100001];
bitset <100001> del;
struct Set
{
int id;
long long d;
Set(int a=0,long long b=0): id(a),d(b) {}
bool operator < (const Set& a) const
{
return d<a.d;
}
};
multiset <Set> st;
bool Check(long long k)
{
if (k==0) return true;
k+=sum;
st.clear();
for (int i=1;i<=n;i++) w[i]=c[i],f[i]=i,st.insert(Set(i,w[i])),del[i]=0;
int curr=1;
while (!st.empty())
{
long long val=(*st.begin()).d;
bool pd=0;
while (curr<=m&&s[curr].w>=k-val)
{
int t1=Find(s[curr].a),t2=Find(s[curr].b);
if (t1!=t2)
{
if (!del[t1]) st.erase(Set(t1,w[t1]));
if (!del[t2]) st.erase(Set(t2,w[t2]));
f[t1]=t2,w[t2]+=w[t1];
if (!del[t1]||!del[t2]) st.insert(Set(t2,w[t2])),del[t2]=0,pd=1;
}
curr++;
}
if (!pd) del[(*st.begin()).id]=true,st.erase(st.begin());
}
int cnt=0;
for (int i=1;i<=n;i++) if (f[i]==i) cnt++;
if (cnt==1) return true;
else return false;
}
//#include<ctime>
int main()
{
// srand((unsigned)time(0));
// n=100000,m=100000;
// int t=0;
// for (int i=2;i<=n;i++) t++,s[t].a=i,s[t].b=rand()%(i-1)+1,s[t].w=rand()*rand();
// while (t<m)
// {
// t++;
// s[t].a=rand()%n+1,s[t].b=rand()%n+1,s[t].w=rand()*rand();
// }
// for (int i=1;i<=n;i++) c[i]=rand()*rand(),sum+=c[i];
// for (int i=1;i<=n;i++) printf("%lld ",c[i]); printf("\n");
// for (int i=1;i<=m;i++) printf("%d %d %lld\n",s[i].a,s[i].b,s[i].w);
n=Read(),m=Read();
for (int i=1;i<=n;i++) c[i]=Read(),sum+=c[i];
for (int i=1;i<=m;i++)
{
s[i].a=Read(),s[i].b=Read(),s[i].w=Read();
}
sort(s+1,s+m+1,cmp);
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=m;i++) tem[i]=s[i];
int tt=m;
m=0;
for (int i=1;i<=tt;i++)
{
int t1=Find(tem[i].a),t2=Find(tem[i].b);
if (t1!=t2)
{
s[++m]=tem[i];
f[t1]=t2;
}
}
long long x=0,y=1e9+1;
while (x+1<y)
{
long long mid=(x+y)/2;
if (Check(mid)) x=mid;
else y=mid;
}
if (x==0) printf("-1");
else printf("%lld",x);
return 0;
}