zoukankan      html  css  js  c++  java
  • 【JZOJ3301】家族【并查集】

    题目大意:

    题目链接:https://jzoj.net/senior/#main/show/3301
    一个无向图的每条边都有一个边权,选择一个区间[l,r][l,r],然后把这个图中边权不在[l,r][l,r]的边全部删掉。会形成多个连通块。大小为ii的连通块的权值为kik_i,求一个rlr-l尽量小的区间使得剩余连通块的权值和sgeq s


    思路:

    暴力想法:枚举左端点,然后二分右端点,用并查集判断这个区间是否满足条件。时间复杂度O(m2logm)O(m^2log m),期望得分50pts50pts
    但是我们发现右端点为rr时,是可以在很快的时间内转移为右端点为r+1r+1的情况。所以我们可以固定左端点,然后指针从左往右扫描右端点,每次把权值和进行一下简单的转移就可以了。时间复杂度O(m2)O(m^2)


    代码:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    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
    ",ans);
    		else printf("T_T
    ");
    	return 0;
    }
    

    我真是太菜了,考试3h3h看错题目,最后十几分钟才发现,然后暴力还写挂45pts45pts。。。
    qwqqwq

  • 相关阅读:
    实习项目1.
    try catch finally的用法
    asp.net 验证控件
    数据库操作语言
    webform Response的一些成员
    jQuery
    C#@的用法
    SQL分页查询
    抽象类与接口的区别
    抽象类与接口
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998124.html
Copyright © 2011-2022 走看看