题目链接:https://jzoj.net/senior/#main/show/3301
一个无向图的每条边都有一个边权,选择一个区间 [ l , r ] [l,r] [l,r],然后把这个图中边权不在 [ l , r ] [l,r] [l,r]的边全部删掉。会形成多个连通块。大小为 i i i的连通块的权值为 k i k_i ki,求一个 r − l r-l r−l尽量小的区间使得剩余连通块的权值和 ≥ s \geq s ≥s。
暴力想法:枚举左端点,然后二分右端点,用并查集判断这个区间是否满足条件。时间复杂度 O ( m 2 log m ) O(m^2\log m) O(m2logm),期望得分 50 p t s 50pts 50pts。
但是我们发现右端点为 r r r时,是可以在很快的时间内转移为右端点为 r + 1 r+1 r+1的情况。所以我们可以固定左端点,然后指针从左往右扫描右端点,每次把权值和进行一下简单的转移就可以了。时间复杂度 O ( m 2 ) O(m^2) O(m2)。
#include
#include
#include
using namespace std;
typedef long long ll;
const int N=5010;
int n,m,x,y,tot,father[N],cnt[N];
ll love[N],ans,s,z;
struct edge
{
int to,from;
ll dis;
}e[N];
void add(int from,int to,ll dis)
{
e[++tot].to=to;
e[tot].from=from;
e[tot].dis=dis;
}
int find(int x)
{
return x==father[x]?x:father[x]=find(father[x]);
}
bool cmp(edge x,edge y)
{
return x.dis<y.dis;
}
int main()
{
scanf("%d%d%lld",&n,&m,&s);
for (int i=1;i<=n;i++) scanf("%lld",&love[i]);
for (int i=1;i<=m;i++)
{
scanf("%d%d%lld",&x,&y,&z);
add(x,y,z);
}
sort(e+1,e+1+m,cmp);
ans=1e17;
for (int i=1;i<=m;i++)
{
for (int j=1;j<=n;j++)
father[j]=j,cnt[j]=1;
ll sum=love[1]*(ll)n;
for (int j=i;j<=m;j++)
if (e[j].dis-e[i].dis<ans)
{
int x=find(e[j].from),y=find(e[j].to);
if (x==y) continue;
sum=sum-love[cnt[x]]-love[cnt[y]];
cnt[x]+=cnt[y]; cnt[y]=0;
father[y]=x;
sum=sum+love[cnt[x]];
if (sum>=s) ans=e[j].dis-e[i].dis;
}
}
if (ans<1e17) printf("%lld\n",ans);
else printf("T_T\n");
return 0;
}
我真是太菜了,考试 3 h 3h 3h看错题目,最后十几分钟才发现,然后暴力还写挂 45 p t s 45pts 45pts。。。
q w q qwq qwq