图:图由顶点和边组成。顶点代表对象。
图的表示:有两种(1)邻接矩阵(2)邻接表;
图的种类:有向图,无向图;
无向图中的一些术语:
路径:相邻顶点的序列;
圈:起点和终点重合的路径;
连通图:任意两点之间都有路径连接的图;
度:顶点连接的边数;没有圈的连通图叫做树,没有圈的非连通图叫做森林;
有向图的术语:
入度,出度;
图的表示:
(1)邻接矩阵:对应于有向图,无向图,是否有权值;浪费空间
(2)邻接表:对应于有向图,无向图,是否有权值。节约空间
图的搜索:
二分图的判定:给定一个具有那个顶点的图,给每个顶底涂色,使得相邻的顶点颜色不同。问是否能最多用两种颜色进行染色?
首先使用邻接矩阵(或邻接表)来表示这个图然后dfs就可以解决。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#define pi acos(-1)
using namespace std;
typedef long long ll;
const int maxn=1e3+10;
const int INF=0x3f3f3f3f;
const double EPS = 1e-10;
inline int read(){
int ret=0,f=0;char ch=getchar();
while(ch>'9'||ch<'0') f^=ch=='-',ch=getchar();
while(ch<='9'&&ch>='0') ret=ret*10+ch-'0',ch=getchar();
return f?-ret:ret;
}
vector<int>G[maxn];
int v;//顶点数
int color[maxn];//顶点颜色(1 or -1) ;
bool dfs(int v,int c){
color[v]=c;
for(int i=0;i<G[v].size();i++){
if(color[G[v][i]]==c)return false;
if(color[G[v][i]]==0&&!dfs(G[v][i],-c))return false;
}
return true;
}
void solve(){
for(int i=0;i<v;i++){
if(color[i]==0){
if(!dfs(i,1)){
cout<<"NO"<<endl;
return ;
}
}
}
cout<<"YES"<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin>>v;
for(int i=0;i<v*2;i++){
int s,t;
cin>>s>>t;
G[s].push_back(t);
}
solve();
return 0;
}
刚开始学习图。