用vector来存储每个边的起点和终点,然后用一个二维vector数组
存储边的信息。
示例:
8 9
1 2 //0号边
1 3 //1号边
1 4 //2号边
2 5 //3号边
2 6 //4号边
3 7 //5号边
4 7 //6号边
4 8 //7号边
7 8 //8号边
二维vector中的存储会如下所示:
0 1 2 //1号顶点连着0、1、2号边
3 4 //2号顶点连着3、4号边
5 //3号顶点连着5号边
6 7 //4号顶点连着6、7号边
//5号顶点没有边
//6号顶点没有边
8 //7号顶点连着8号边
//8号顶点没有边
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct edge
{
int u,v;
};
vector<int>e[100001];//编号边连点信息
vector<edge>s;//具体信息
bool cmp(edge x,edge y)//按原终点排序
{
if(x.u==y.u)
return x.v<y.v;
else return x.u<y.u;
}
int a[100001]={0};//存所连最大的点
void dfs(int x)
{
for(int i=0;i<e[x].size();i++)
{
int ans=s[e[x][i]].v;
if(a[x]>a[ans])
a[ans]=a[x];
}
if(x>1)
dfs(x-1);
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int u1,v1;
cin>>u1>>v1;
//反向存边
s.push_back((edge){v1,u1});
}
sort(s.begin(),s.end(),cmp);
for(int i=0;i<m;i++)
{
e[s[i].u].push_back(i);//与原终点相连的是几号边
}
for(int i=1;i<=n;i++)//初始化结果,每条边都能到自己
{
a[i]=i;
}
dfs(n);
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
}