P3916 圖的遍歷(反向建邊,bfs)

題目傳送門

題意: 給你一張有向圖,假設A(x)表示從x出發能到達的最大的點,輸出A(1~n) 。

思路: 我們不妨反向建邊,從x出發到的最大的點,就轉換成從大點能走到哪些點,反向建邊之後依次從大的點遍歷,每次成功走到一些點就把點打標記避免重複詢問同一個點導致答案錯誤。

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define pii pair<int,int>
#define ull unsigned long long
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read(){int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();}
return x*f;}
using namespace std;
const int N=1e5+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-7;
const double PI=acos(-1);
vector<int>e[N];int ans[N];
void bfs(int x)
{
    ans[x]=x;
    queue<int>q;
    q.push(x);
    while(!q.empty())
    {
        int t=q.front();q.pop();
        for(auto i:e[t])
        {
            if(!ans[i])
            {q.push(i);
            ans[i]=x;}
        }
    }
}
signed main()
{
    int n=read(),m=read();
    while(m--)
    {
        int u=read(),v=read();
        e[v].pb(u);
    }
    for(int i=n;i>=1;i--)
    {
        if(!ans[i])
        {
            bfs(i);
        }
    }
    for(int i=1;i<=n;i++)
        cout<<ans[i]<<' ';
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章