拓扑排序的时间复杂度是:O(n+m)
板子题:hihocoder-1174
链式前向星写法:
#include<bits/stdc++.h>
#define ll int
#define endl '\n'
#define IO ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e5+5;
ll n,m,num,tot=1;
ll InDeg[maxn],head[maxn];
queue<ll> q;
struct E{
int to,next;
}edge[maxn<<1];
inline void add(int u,int v){
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
bool topsort(){
while(!q.empty()) q.pop();
num=0;
for(int i=1;i<=n;i++) if(!InDeg[i]) q.push(i);
while(!q.empty()){
ll now=q.front();
q.pop();
num++;
for(int i=head[now];i;i=edge[i].next){
int v=edge[i].to;
if(--InDeg[v]==0) q.push(v);
}
}
if(num==n) return true;
else return false;
}
int main(){
int T;cin>>T;
while(T--){
cin>>n>>m;
memset(edge,0,sizeof(edge));
memset(InDeg,0,sizeof(InDeg));
memset(head,0,sizeof(head));
while(m--){
ll u,v;cin>>u>>v;
InDeg[v]++;
add(u,v);
}
if(topsort()) puts("Correct");
else puts("Wrong");
}
}
临接矩阵vector写法:
#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
const int maxn=1e5+10;
ll n,m,num;
ll InDeg[maxn];
vector<ll> vec[maxn];
queue<ll> q;
bool topsort(){
while(!q.empty()) q.pop();//初始化清空队列
num=0;
for(ll i=1;i<=n;i++) if(!InDeg[i]) q.push(i);//遍历寻找入度为0的点加入队列
while(!q.empty()){
ll now=q.front();
q.pop();
num++;//如果该点入度为0,则加入到拓扑序列之中去
for(ll i=0;i<vec[now].size();i++){
if(--InDeg[vec[now][i]]==0) q.push(vec[now][i]);
//先减少该后继点的前驱数量
//如果前驱数量为0,则加入到拓扑序列之中
}
}
if(num==n) return true;
else return false;
}
int main(){
ll T;cin>>T;
while(T--){
cin>>n>>m;
for(ll i=1;i<=n;i++) vec[i].clear(); //后继初始化清空
memset(InDeg,0,sizeof(InDeg));//入度初始化清空
while(m--){
ll u,v;cin>>u>>v;
vec[u].push_back(v);//添加后继
InDeg[v]++;//添加入度
}
if(topsort()) puts("Correct");
else puts("Wrong");
}
}
hihocoder-1175
#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int mod=142857;
const int maxn=1e5+10;
ll InDeg[maxn],virus[maxn];
vector<ll> vec[maxn];
queue<ll> q;
ll n,m,k;
void topsort(){
while(!q.empty()) q.pop();
for(ll i=1;i<=n;i++){
if(InDeg[i]==0) q.push(i);
}
while(!q.empty()){
ll now=q.front();
q.pop();
for(ll i=0;i<vec[now].size();i++){
if(--InDeg[vec[now][i]]==0) q.push(vec[now][i]);
virus[vec[now][i]]=(virus[vec[now][i]]+virus[now])%mod;
}
}
}
int main(){
while(cin>>n>>m>>k){
for(ll i=1;i<=n;i++) vec[i].clear();
memset(InDeg,0,sizeof(InDeg));
memset(virus,0,sizeof(virus));
while(k--){
ll x;cin>>x;
virus[x]++;
}
for(ll i=1;i<=m;i++){
ll u,v;cin>>u>>v;
vec[u].push_back(v);
InDeg[v]++;
}
topsort();
ll ans=0;
for(ll i=1;i<=n;i++) ans=(ans+virus[i])%mod;
cout<<ans<<endl;
}
}