题目:http://acm.hdu.edu.cn/showproblem.php?pid=3342
题意:判断有无环
#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const ll _max = 505;
int n,m;
int mp[_max][_max];
int ft[_max];
void topsort(){
priority_queue<int,vector<int>,greater<int> > q;
while(!q.empty()) q.pop();
int cnt = 0;
for(int i = 0 ; i < n ; i++){
if(!ft[i]){
q.push(i);
cnt++;
}
}
int id = 0;
while(!q.empty()){
id = q.top();
q.pop();
for(int i = 0 ; i < n ; i++){
if(mp[id][i]){
ft[i]--;
if(!ft[i]){
q.push(i);
cnt++;
}
}
}
}
if(cnt == n) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return ;
}
int main(){
IOS;
while(cin>>n>>m){
if(!n&&!m) break;
memset(mp,0,sizeof(mp));
memset(ft,0,sizeof(ft));
int u,v;
for(int i = 1 ; i <= m ; i++){
cin>>u>>v;
if(!mp[u][v]){
mp[u][v] = 1;
++ft[v];
}
}
topsort();
}
return 0;
}
这是最开始的代码,就直接判断用队列排进多少节点,然后和n进行对比。就知道有没有环了,因为拓扑排序里,有环是排不进的。但是太慢了200ms,我看了下别人是0ms的。
然后看了下代码,我这里时间久应该是因为我用数组模拟的树状结构。所以慢,所以换成邻接表。
#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const ll _max = 505;
struct node{
int to;
struct node *next;
};
node *List[_max];
int n,m;
int ft[_max];
void topsort(){
priority_queue<int,vector<int>,greater<int> > q;
while(!q.empty()) q.pop();
int cnt = 0;
for(int i = 0 ; i < n ; i++){
if(!ft[i]){
q.push(i);
cnt++;
}
}
int id = 0;
node *temp;
while(!q.empty()){
id = q.top();
q.pop();
temp = List[id];
while(temp!=NULL){
id = temp->to;
if(--ft[id]==0){
q.push(id);
cnt++;
}
temp = temp->next;
}
}
if(cnt == n) printf("YES\n");
else printf("NO\n");
return ;
}
int main(){
while(~scanf("%d%d",&n,&m)){
if(!n&&!m) break;
memset(List,0,sizeof(List));
memset(ft,0,sizeof(ft));
int u,v;
node *temp;
for(int i = 1 ; i <= m ; i++){
scanf("%d%d",&u,&v);
ft[v]++;
temp = new node;
temp->to = v;
temp->next = NULL;
if(List[u]==NULL)
List[u]=temp;
else{
temp->next=List[u];
List[u]=temp;
}
}
topsort();
for(int i = 0 ; i < n ; i++){
temp = List[i];
while(temp!=NULL){
List[i] = temp->next;
delete temp;
temp = List[i];
}
}
}
return 0;
}
这里换了领接表31ms就行了。