我比较懒,直接用priority_queue写,但是我加了一个找根的操作就 WA4,后面我直接改成从 1 搜索就AC,为什么嘞?求助!!
代码:
//WA4
#include<bits/stdc++.h>
#define ll long long
#define reg register
using namespace std;
const int maxn=1e5+5;
struct point {
priority_queue<int,vector<int>,greater<int> >son1;
priority_queue<int,vector<int>,greater<int> >son2;
} a[maxn];
inline int read() {
int f=1,x=0;
char ch=getchar();
while(ch>'9'||ch<'0') {
if(ch=='-')f*=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
int vis[maxn],In[maxn];
void dfs(int rt) {
vis[rt]=1;
printf("%d ",rt);
while(a[rt].son1.size()) {
reg int v=a[rt].son1.top();
a[rt].son1.pop();
if(!vis[v])dfs(v);
}
}
void bfs(int rt) {
memset(vis,0,sizeof(vis));
queue<int>q;//,vector<int>,greater<int>
q.push(rt);
vis[rt]=1;
while(!q.empty()) {
int u=q.front();
q.pop();
//if(vis[u])continue;
//vis[u]=1;
printf("%d ",u);
while(a[u].son2.size()) {
reg int v=a[u].son2.top();
a[u].son2.pop();
if(!vis[v])q.push(v),vis[v]=1;
}
}
}
int main() {
reg int n=read(),m=read();
reg int u,v;
for(reg int i(1); i<=m; ++i) {
u=read(),v=read();
a[u].son1.push(v);
a[u].son2.push(v);
In[v]++;
}
int rt;
for(reg int i=1; i<=n; ++i) {
if(!In[i]) {
rt=i;
break;
}
}
dfs(rt);
//dfs(1);改成这个就AC
puts("");
bfs(rt);
//bfs(1);改成这个就AC
return 0;
}