自己写的代码:1ms
这题数据比较小,所以不会超时,如果数据较大,还是用拓扑排序
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<vector>
using namespace std;
int a[105];
int n,m;
int x,y;
void judge()
{
int x1,y1;
for(int i=1;i<=n;i++)
{
if(x==a[i])x1=i;
else if(y==a[i])y1=i;
}
if(x1>y1)
{
int t=a[x1];a[x1]=a[y1];a[y1]=t;
}
}
int main()
{
//freopen("f.txt","r",stdin);
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)break;
for(int i=1;i<=n;i++)
a[i]=i;
for(int i=1;i<=m;i++)
{
cin>>x>>y;
judge();
}
for(int i=1;i<n;i++)
cout<<a[i]<<' ';
cout<<a[n]<<endl;
}
return 0;
}
书上的拓扑排序:用时更短
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=105;
int c[maxn];
int topo[maxn],t,G[maxn][maxn],n;
bool dfs(int u)
{
c[u]=-1;
for(int v=1;v<=n;v++)
if(G[u][v])
{
if(c[v]<0)return false;
else if(!c[v]&&!dfs(v))return false ;
}
c[u]=1;topo[--t]=u;
return true;
}
bool toposort()
{
t=n;
memset(c,0,sizeof(c));
for(int u=1;u<=n;u++) if(!c[u])
if(!dfs(u))return false;
return true;
}
int main()
{
//freopen("f.txt","r",stdin);
int m,i;
while(scanf("%d%d",&n,&m),n || m)
{
int u,v;
memset(G,0,sizeof(G));
for(i = 0 ; i < m ; i++)
{
scanf("%d%d",&u,&v);
G[u][v] = 1;
}
if(toposort())
{
for(i = 0; i < n-1; i++)
printf("%d ",topo[i]);
printf("%d\n",topo[i]);
}
}
return 0;
}