为什么我的拓扑这么慢
  • 板块P2712 摄像头
  • 楼主Eryi117
  • 当前回复1
  • 已保存回复1
  • 发布时间2025/7/19 15:35
  • 上次更新2025/7/19 15:42:39
查看原帖
为什么我的拓扑这么慢
1139280
Eryi117楼主2025/7/19 15:35

除了快读快输还能优化吗?

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e6+5;
int n;
vector<vector<int>>e(N);//图
vector<int>din(N,0),tp;//每个点的入度,拓扑序
vector<int>vis(N);//摄像头照到的地方不一定有摄像头需要判断
int ans=0;
bool toposort() {
    queue<int> q;
    for (int i = 1; i <= 505; i++) {
        if (din[i] == 0&&vis[i]) q.push(i);
    }
    while(!q.empty()){
        int u = q.front(); q.pop();
        tp.push_back(u);
        for (int v : e[u]) {
            if (--din[v] == 0&&vis[v]) {
                q.push(v);
            }
        }
    }
    return (int)tp.size() == n;
}

void solve(){
    cin>>n;
    tp.clear();
    for(int i=0;i<n;i++){
        int x,m;cin>>x>>m;
        vis[x]=1;
        for(int j=0;j<m;j++){
            int y;cin>>y;
            e[x].push_back(y);
            din[y]++;
        }
    }
    if(toposort())cout<<"YES";
    else cout<<n-tp.size()<<endl;
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t=1;
    while(t--)solve();
    return 0;
}

提交地址

2025/7/19 15:35
加载中...