标签:des style blog http color strong
题目链接:
题目:
| Time Limit: 1000MS | Memory Limit: 65536K | |||
| Total Submissions: 2704 | Accepted: 1816 | Special Judge | ||
Description
Input
Output
Sample Input
5 0 4 5 1 0 1 0 5 3 0 3 0
Sample Output
2 4 5 3 1
Source
这个题目是拓扑排序的入门题。。
首先在这里一个讲的非常好的链接:
我用了两种方法做这个题。
第一种是利用入度为0的点必然是前面的点,然后删除从这个点到其他点的边,最后一期输出结果。。速度很快。
第二种是利用dfs搜索,直到搜索到已经访问到的点,然后利用栈来保存。。最后利用栈的性质来输出即可。。
第二中代码为:
#include<cstdio>
#include<iostream>
#include<stack>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100+10;
int vis[maxn],map[maxn][maxn];
int n,t;
stack<int>S;
bool dfs(int u)
{
vis[u]=-1;
for(int v=1;v<=n;v++)
if(map[u][v])
{
// if(vis[v]<0) return false;
if(!vis[v]&&!dfs(v)) return false;
}
vis[u]=1;
S.push(u);
return true;
}
bool toposort()
{
memset(vis,0,sizeof(vis));
for(int u=1;u<=n;u++)
{
if(!vis[u])
{
if(!dfs(u))
return false;
}
}
return true;
}
int main()
{
int u;
bool ok;
while(scanf("%d",&n)!=EOF)
{
t=n;
memset(map,0,sizeof(map));
for(int i=1;i<=n;i++)
{
while(1)
{
scanf("%d",&u);
if(u==0)
break;
map[i][u]=1;
}
}
ok=toposort();
if(ok)
{
while(!S.empty())
{
int val=S.top();
if(t!=1)
printf("%d ",val);
else
printf("%d\n",val);
S.pop();
t--;
}
}
}
return 0;
}
第一种方法代码:
#include<cstdio>
#include<cstring>
const int maxn=100+10;
int map[maxn][maxn],into[maxn],ans[maxn],vis[maxn];
int pos;
int main()
{
int n,u,temp;
while(~scanf("%d",&n))
{
pos=0;
memset(map,0,sizeof(map));
memset(into,0,sizeof(into));
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
while(1)
{
scanf("%d",&u);
if(u==0)
break;
map[i][u]=1;
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(map[i][j])
into[j]++;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(into[j]==0&&!vis[j])
{
temp=j;
vis[j]=1;
ans[pos++]=temp;
for(int m=1;m<=n;m++)
{
if(map[temp][m])
into[m]--;
}
}
}
for(int i=0;i<pos;i++)
{
if(i!=pos-1)
printf("%d ",ans[i]);
else
printf("%d\n",ans[i]);
}
}
return 0;
}
poj2367Genealogical tree,布布扣,bubuko.com
标签:des style blog http color strong
原文地址:http://blog.csdn.net/u014303647/article/details/37081775