E. Edge Reverse

E. Edge Reverse

思路

二分建图,然后缩点。
如果只有1个点入度为0,那就是满足条件的

代码

#include <bits/stdc++.h>
using namespace std;
using pii=pair<int,int>;
using pdd=pair<double,double>;
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define TT int _=read();while(_--)
#define int long long
using ll=long long;
const ll inf=1e18;
//#define double long double
#define endl '\n'
const int M=2e5+5;

inline int read(){
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    return x*f;
}

inline void print(int x) {
    if(x<0){putchar('-');x=-x;}
    if(x/10)print(x/10);
    putchar(x%10+'0');
}

int n,m;
int u[M],v[M],w[M];

int h1[M],h2[M],ne[M<<2],e[M<<2],tot;
void add(int h[],int from,int to) {
    e[++tot]=to;  ne[tot]=h[from];  h[from]=tot;
}

int dfn[M],low[M],cnt;
int id[M],scnt;
bool vis[M];
stack<int>st;
void tarjan(int now) {
    dfn[now]=low[now]=++cnt;
    st.push(now);
    vis[now]=1;
    for(int i=h1[now];i;i=ne[i]) {
        int to=e[i];
        if(dfn[to]==0) {
            tarjan(to);
            low[now]=min(low[now],low[to]);
        }
        else if(vis[to])low[now]=min(low[now],dfn[to]);//这里是dfn
    }
    if(dfn[now]==low[now]) {
        scnt++;
        while(1) {
            int k=st.top();
            st.pop();
            vis[k]=0;
            id[k]=scnt;
            if(k==now)break;
        }
    }
}

int in[M];
void init() {
    cnt=scnt=0;
    for(int i=1;i<=n;i++)dfn[i]=vis[i]=low[i]=id[i]=in[i]=0;
    for(int i=1;i<=n;i++)if(dfn[i]==0)tarjan(i);//缩点
    for(int i=1;i<=n;i++)//重构图
        for(int j=h1[i];j;j=ne[j]) {
            int to=e[j];
            if(id[i]!=id[to]) {
                add(h2,id[i],id[to]);
                in[id[to]]++;
            }
        }//图建好了
}

bool check(int x) {
    tot=0;
    for(int i=1;i<=n;i++)h1[i]=h2[i]=0;//清空
    for(int i=1;i<=m;i++) {
        add(h1,u[i],v[i]);
        if(w[i]<=x)add(h1,v[i],u[i]);
    }//第一次建图
    init();
    
    int f=0;
    for(int i=1;i<=scnt;i++)
        if(!in[i])f++;
    return f==1;
    //一共有scnt个点
}
//也就是缩点走图
//两个环的话,也是不行的
//也就是有环的存在,所以有干扰


signed main() {
    TT {
        n=read(),m=read();
        for(int i=1;i<=m;i++) {
            u[i]=read();
            v[i]=read();
            w[i]=read();
        }
        int l=0,r=1e9,ans=-1;
        while(l<=r) {
            int mid=(l+r)/2;
            if(check(mid))ans=mid,r=mid-1;
            else l=mid+1;
        }
        cout<<ans<<'\n';
    }
    return 0;
}
//二分,然后把那些边能双向找出来就可以了
//然后怎么判断这个点可以到达其他的所有的点呢??
//出度为0的点只有1个,检查一下子就可以了
//难道是判断的条件有问题吗
posted @ 2023-02-12 23:15  basicecho  阅读(33)  评论(0)    收藏  举报