一。用结构体
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<iostream>
#include<algorithm>
using namespace std;
struct Edge{
int to;
int cost;
};
vector <Edge> G[10000]; //G[i]代表从i出发的边,vector里存的是边
int m,n;
int temp;
int main(void)
{
cin>>n>>m; //m是边的条数,n是点的个数
while(m--)
{
Edge e;
cin>>temp>>e.to>>e.cost;
G[temp].push_back(e);
}
//遍历
for(int i=1;i<=n;i++)
{
for(int j=0;j<G[i].size();j++)//每条边
{
Edge e=G[i][j];
cout<<i<<"->"<<e.to<<" :"<<e.cost<<endl;
}
}
return 0;
}
这种方法用vector存的是每条边
二。用vector存点,建立邻接表,只需要计算每个点的度时邻接表好用
#include<bits/stdc++.h>
using namespace std;
const int maxn=200001;
int n,m,vis[maxn],ans,f;
vector<int>v1[maxn];
void dfs(int x)
{
vis[x]=1; //下面是读取每个点所相邻的点的过程
for(int i=1;i<v1[x].size;i++){
int k=v1[x][i];
if(!vis[k])
dfs(k);
}
if(v1[x].size()!=2)
f=0;
}
int main()
{
cin>>n>>m; //下面是存点输入进去的过程
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
v1[x].push_back(y);
v1[y].push_back(x);
}
for(int i=1;i<=n;i++)
{
f=1;
if(!vis[i]){
dfs(i);
ans+=f;
}
}
}
下面是第二种建立邻接表方法的题