邻接表表示图
struct Edge{
int nextNode;//下一个结点编号
int cost;//该边的权重
};
int main()
{
vector<Edge> edge[N];
for(int i=0;i<=N;i++)//初始化
edge[i].clear();
for(int i=0;i<N;i++)
{
int tempa,tempb,cost;
Edge tempe;
cin>>tempa>>tempb>>cost;
tempe.nextNode=tempb;
tempe.cost=cost;
edge[tempa].push_back(tempe);
for(int i=0;i<N;i++)//遍历
{
for(int j=0;j<edge[i].size();j++)
{
int nextNode = edge[i][j].nextNode;
int cost = edge[i][j].cost;
}
}
edge[1].erase(edge[1].begin()+5,edge[1].begin()+6);//删除结点1与结点5的路径
}
}
并查集
int findRoot(int x)
{
if(Tree[x]!=-1)
{
int tmp = findRoot(Tree[x]);//路径压缩
Tree[x]=tmp;
return tmp;
}
return x;
}
int findRoot2(int x)
{
int tmp=x;
while(Tree[x]!=-1)
x=Tree[x];
int root=x;
while(Tree[x]!=-1)//路径压缩
{
int t=Tree[x];
Tree[x]=root;
x=t;
}
return root;
}
最小生成树(Kruskal算法)
struct Edge{
int a,b;//顶点
int cost;//权值
}edge[100];
int Tree[N];
bool cmp(Edge v1,Edge v2)//按照路径的权重排序
{
return v1.cost<v2.cost;
}
int findRoot(int x)
{
if(Tree[x]!=-1)
{
int tmp = findRoot(Tree[x]);//路径压缩
Tree[x]=tmp;
return tmp;
}
return x;
}
int main()
{
int n,tempa,tempb,cost;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>tempa>>tempb>>cost;
edge[i].a=tempa;
edge[i].b=tempb;
edge[i].cost=cost;
}
sort(edge,edge+n,cmp);
for(int i=0;i<n;i++)
Tree[i]=-1;
int ans=0;
for(int i=0;i<n;i++)
{
int a=findRoot(edge[i].a);
int b=findRoot(edge[i].b);
if(a!=b)
{
Tree[a]=b;
ans+=edge[i].cost;
}
}
cout<<ans<<endl;
}
最短路径(dijstra)
int n,m;
cin>>n>>m;
int dst[N] = {MAXDST};
int flag[N] = {0};
for(int i=0;i<=n;i++)
{
for(int j=0;j<=n;j++)
edge[i][j] = MAXDST;
edge[i][i] = 0;
}
dst[1] = 0;
flag[1] = 1;
for(int i=1;i<=m;i++)
{
int tempi,tempj,tempw;
cin>>tempi>>tempj>>tempw;
edge[tempi][tempj] = tempw;
}
for(int i=1;i<=n;i++)
dst[i] = edge[1][i];
for(int i=1;i<=n;i++)
{
int mindst = MAXDST;
int u = 1;
for(int j=1;j<=n;j++)
{
if(flag[j]==0&&dst[j]<mindst)
{
u = j;
mindst = dst[j];
}
}
flag[u] = 1;
for(int j=1;j<=n;j++)
{
if(flag[j]==0&&edge[u][j]<MAXDST)
{
if(dst[j]>dst[u]+edge[u][j])
{
dst[j] = dst[u] + edge[u][j];
}
}
}
}
cout<<dst[n]<<endl;
拓扑排序
vector<int> edge[N];
queue<int> Q;//入度为0的结点队列
int inDegree[N];//所有结点的入度
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
{
inDegree[i]=0;
edge[i].clear();
}
while(m--)
{
int a,b;
cin>>a>>b;
inDegree[b]++;
edge[a].push_back(b);
}
while(!Q.empty())//清空队列
Q.pop();
int cnt=0;
while(!Q.empty())
{
int nowP=Q.front();
Q.pop();
cnt++;
for(int i=0;i<edge[nowP].size();i++)
{
inDegree[edge[nowP][i]]--;
if(inDegree[edge[nowP][i]]==0)
Q.push(edge[nowP][i]);
}
}
if(cnt==n) cout<<"Yes\n";
else cout<<"No\n";