图论模板,不定期更新

图论模板,随缘不定期更新

  • 网络流
    • 最大流
      • dinic(更新于2021/1/6)
      • hlpp(更新于2021/1/6)
    • 最小费用最大流(更新于2021/1/6)
    • 无源汇有上下界可行流(更新于2021/1/6)
    • 有源汇上下界最大流(更新于2021/1/6)
  • 最短路径
    • dijkstra(更新于2021/1/6)
    • spfa(更新于2021/1/6)
  • 最小生成树
    • kruskal(更新于2021/1/6)
    • prim(更新于2021/1/6)
  • 欧拉通路与欧拉回路
    • 并查集(更新于2021/1/6)
    • 判断存在欧拉回路(更新于2021/1/6)
    • 寻找欧拉路径(更新于2021/1/6)
  • prufer编码
    • prufer编码转树(更新于2021/1/6)
  • LCA(更新于2021/1/6)
  • tarjan求割点(更新于2021/1/6)

用来保存图论的模板方便备赛,算法的解析看心情写—Ninght

网络流

最大流

dinic(更新于2021/1/6)

//输入顶点数,边数,源点,汇点及各有向边的起始点和权值,输出汇点最大流
#include
#include
#include
#include
#define int long long
using std::queue;
struct node {
     
	int to;//终点
	int next;//与该边同起点的上一条边的序号
	int w;//权值
}qxx[200005];//边集链式前向星
int h[200005];//起点为x的一条边的序号
int cnt;//计数器
int n, m, st, en;//顶点数,边数,源点,汇点
int x, y, z;//始点,终点,权值
void add(int x, int y, int z) {
     
	qxx[++cnt] = node{
      y,h[x],z };
	h[x] = cnt;
}//添加边(始点,终点,权值)
void ad(int x, int y, int z) {
     
	add(x, y, z);//正向
	add(y, x, 0);//反向
}//添加边
int d[200005];
bool bfs() {
     
	memset(d, 0, sizeof d);
	queue<int>q;
	while (!q.empty())q.pop();
	d[st] = 1;
	q.push(st);
	while (!q.empty()) {
     
		int x = q.front();
		q.pop();
		for (int i = h[x]; i; i = qxx[i].next) {
     
			int v = qxx[i].to;
			if (!d[v] && qxx[i].w) {
     
				d[v] = d[x] + 1;
				q.push(v);
				if (v == en)return true;
			}
		}
	}
	return false;
}
int dfs(int u, int flow) {
     
	if (u == en)return flow;
	int rest = flow;
	for (int i = h[u]; i; i = qxx[i].next) {
     
		int v = qxx[i].to;
		if (d[v] == d[u] + 1 && qxx[i].w) {
     
			int tmp = dfs(v, std::min(qxx[i].w, rest));
			if (!tmp)d[v] = 0;
			rest -= tmp;
			qxx[i].w -= tmp;
			qxx[i ^ 1].w += tmp;
			if (!rest)break;
		}
	}
	return flow - rest;
}
int ans, sth;
signed main() {
     
	scanf_s("%lld%lld%lld%lld", &n, &m, &st, &en);
	for (int i = 1; i <= m; i++) {
     
		scanf_s("%lld%lld%lld", &x, &y, &z);
		ad(x, y, z);
	}
	while (bfs())while (sth = dfs(st, 1e9))ans += sth;
	printf("%lld", ans);
	return 0;
}

hlpp(更新于2021/1/6)

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long 
#define inf 0x3f3f3f3f
#define re register
#define il inline
using namespace std;
struct edge
{
     
    int to, next;
    int flow;
}a[2000020];//链式前向星 
int head[10010];
int gap[10010];//存储同层结点数
int h[10010];
int e[10010];//e[i]表示第i号节点的超额流
int vis[10010];
int cnt(0);
int n, m, st, ed;//顶点数,边数,源点,汇点
struct cmp
{
     
    il bool operator ()(int xi, int yi)const
    {
     
        return h[xi] < h[yi];
    }
};
priority_queue<int, vector<int>, cmp> pq;//以层数为优先级队列 
queue<int> q;
il void addedge(int xi, int yi, int fi)
{
     
    a[cnt].to = yi;
    a[cnt].next = head[xi];
    a[cnt].flow = fi;
    head[xi] = cnt++;
}
il bool bfs()
{
     
    re int i;
    memset(h + 1, inf, sizeof(int) * n);//将所有的节点高度均设为inf,表示不在网络内
    h[ed] = 0;
    q.push(ed);
    while (!q.empty())
    {
     
        int t = q.front();
        q.pop();
        for (i = head[t]; i != -1; i = a[i].next)
        {
     
            int v = a[i].to;
            if (a[i ^ 1].flow && h[v] > h[t] + 1)
            {
     
                h[v] = h[t] + 1;//更新节点高度
                q.push(v);
            }
        }
    }
    return h[st] != inf;
}
il void push(int u)
{
     
    re int i;
    for (i = head[u]; i != -1; i = a[i].next)//遍历当前点的邻点
    {
     
        int v = a[i].to;
        if ((a[i].flow) && (h[v] + 1 == h[u]))//将该店的超额流传入层数小1的邻点
        {
     
            int df = min(e[u], a[i].flow);
            a[i].flow -= df;
            a[i ^ 1].flow += df;
            e[u] -= df;
            e[v] += df;
            if ((v != st) && (v != ed) && (!vis[v]))
            {
     
                pq.push(v);
                vis[v] = 1;
            }
            if (!e[u])break;
        }
    }
}//只将处源点和汇点以外的点送入队列
il void relabel(int u)
{
     
    re int i;
    h[u] = inf;
    for (i = head[u]; i != -1; i = a[i].next)
    {
     
        int v = a[i].to;
        if ((a[i].flow) && (h[v] + 1 < h[u]))h[u] = h[v] + 1;
    }
}
inline int hlpp()
{
     
    re int i;
    if (!bfs())return 0;
    h[st] = n;
    memset(gap, 0, sizeof(int) * (n << 1));
    for (i = 1; i <= n; i++)if (h[i] != inf)gap[h[i]]++;
    for (i = head[st]; i != -1; i = a[i].next)
    {
     
        int v = a[i].to;
        if (int f = a[i].flow)
        {
     
            a[i].flow -= f; a[i ^ 1].flow += f;
            e[st] -= f; e[v] += f;
            if (v != st && v != ed && !vis[v])
            {
     
                ¬¬pq.push(v);
                vis[v] = 1;
            }
        }
    }
    while (!pq.empty())
    {
     
        int t = pq.top(); pq.pop();
        vis[t] = 0; push(t);
        if (e[t])
        {
     
            gap[h[t]]--;
            if (!gap[h[t]])
            {
     
                for (re int v = 1; v <= n; v++)
                {
     
                    if (v != st && v != ed && h[v] > h[t] && h[v] < n + 1)
                    {
     
                        h[v] = n + 1;
                    }
                }
            }
            relabel(t); gap[h[t]]++;
            pq.push(t); vis[t] = 1;
        }
    }
    return e[ed];
}
signed main()
{
     
    re int i;
    memset(head, -1, sizeof(head));
    scanf_s("%d%d%d%d", &n, &m, &st, &ed);
    for (i = 1; i <= m; i++)
    {
     
        int x, y;
        ll f;
        scanf_s("%d%d%lld", &x, &y, &f);
        addedge(x, y, f);
        addedge(y, x, 0);
    }
    ll maxf = hlpp();
    printf("%lld", maxf);
    return 0;
}

最小费用最大流(更新于2021/1/6)

#include
#include
#include
#include
using namespace std;
const int maxn = 100010;

bool vis[maxn];
int n, m, s, t, x, y, z, f, dis[maxn], pre[maxn], last[maxn], flow[maxn], maxflow, mincost;
//dis最小花费;pre每个点的前驱;last每个点的所连的前一条边;flow源点到此处的流量 
struct Edge {
     
	int to, next, flow, dis;//flow流量 dis花费 
}edge[maxn];
int head[maxn], num_edge;
queue <int> q;

void add_edge(int from, int to, int flow, int dis)
{
     
	edge[++num_edge].next = head[from];
	edge[num_edge].to = to;
	edge[num_edge].flow = flow;
	edge[num_edge].dis = dis;
	head[from] = num_edge;
}

bool spfa(int s, int t)
{
     
	memset(dis, 0x7f, sizeof(dis));
	memset(flow, 0x7f, sizeof(flow));
	memset(vis, 0, sizeof(vis));
	q.push(s); vis[s] = 1; dis[s] = 0; pre[t] = -1;

	while (!q.empty())
	{
     
		int now = q.front();
		q.pop();
		vis[now] = 0;
		for (int i = head[now]; i != -1; i = edge[i].next)
		{
     
			if (edge[i].flow > 0 && dis[edge[i].to] > dis[now] + edge[i].dis)//正边 
			{
     
				dis[edge[i].to] = dis[now] + edge[i].dis;
				pre[edge[i].to] = now;
				last[edge[i].to] = i;
				flow[edge[i].to] = min(flow[now], edge[i].flow);//
				if (!vis[edge[i].to])
				{
     
					vis[edge[i].to] = 1;
					q.push(edge[i].to);
				}
			}
		}
	}
	return pre[t] != -1;
}

void MCMF()
{
     
	while (spfa(s, t))
	{
     
		int now = t;
		maxflow += flow[t];
		mincost += flow[t] * dis[t];
		while (now != s)
		{
     //从源点一直回溯到汇点 
			edge[last[now]].flow -= flow[t];//flow和dis容易搞混 
			edge[last[now] ^ 1].flow += flow[t];
			now = pre[now];
		}
	}
}

int main()
{
     
	memset(head, -1, sizeof(head)); num_edge = -1;//初始化 
	scanf("%d%d%d%d", &n, &m, &s, &t);
	for (int i = 1; i <= m; i++)
	{
     
		scanf("%d%d%d%d", &x, &y, &z, &f);
		add_edge(x, y, z, f); add_edge(y, x, 0, -f);
		//反边的流量为0,花费是相反数 
	}
	MCMF();
	printf("%d %d", maxflow, mincost);
	return 0;
}

无源汇有上下界可行流(更新于2021/1/6)

#include
#include
#include
#include
#define N 100005
#define M 1000005
#define inf 1ll<<31ll-1
using namespace std;
int n, m, s, t, ss, tt, num = 1;
int v[M], w[M], next1[M];
int d[N], f[N], sum[N], first[N];
bool can[N];
void add(int x, int y, int f)
{
     
	num++;
	next1[num] = first[x];
	first[x] = num;
	v[num] = y;
	w[num] = f;
}
bool bfs(int start, int end)
{
     
	int x, y, i, j;
	memset(d, -1, sizeof(d));
	memcpy(f, first, sizeof(f));
	queue<int>q;
	q.push(start);
	d[start] = 0;
	while (!q.empty())
	{
     
		x = q.front();
		q.pop();
		for (i = first[x]; i; i = next1[i])
		{
     
			y = v[i];
			if (w[i] && d[y] == -1 && !can[y])
			{
     
				d[y] = d[x] + 1;
				if (y == end)
					return true;
				q.push(y);
			}
		}
	}
	return false;
}
int dinic(int now, int end, int flow)
{
     
	if (now == end)
		return flow;
	int x, delta, ans = 0;
	for (int& i = f[now]; i; i = next1[i])
	{
     
		x = v[i];
		if (w[i] && d[x] == d[now] + 1 && !can[x])
		{
     
			delta = dinic(x, end, min(flow, w[i]));
			w[i] -= delta;
			w[i ^ 1] += delta;
			flow -= delta;
			ans += delta;
			if (!flow)  break;
		}
	}
	if (flow)  d[now] = -1;
	return ans;
}
int main()
{
     
	int x, y, i, j, l, r;
	int ans = 0, maxflow = 0;
	scanf("%d%d%d%d", &n, &m, &s, &t);
	ss = 0, tt = n + 1;
	for (i = 1; i <= m; ++i)
	{
     
		scanf("%d%d%d%d", &x, &y, &l, &r);
		sum[x] -= l, sum[y] += l;
		add(x, y, r - l), add(y, x, 0);
	}
	for (i = 1; i <= n; ++i)
	{
     
		if (sum[i] > 0)  add(ss, i, sum[i]), add(i, ss, 0), ans += sum[i];
		if (sum[i] < 0)  add(i, tt, -sum[i]), add(tt, i, 0);
	}
	add(t, s, inf), add(s, t, 0);
	while (bfs(ss, tt))
		maxflow += dinic(ss, tt, inf);
	can[ss] = false;
	can[tt] = false;
	if (maxflow != ans)
	{
     
		printf("please go home to sleep");
		return 0;
	}
	int minflow = 0;
	add(t, s, -inf), add(s, t, 0);
	while (bfs(t, s))
		minflow -= dinic(t, s, inf);
	printf("%d", minflow);
	return 0;
}

有源汇上下界最大流(更新于2021/1/6)

#include
#include
#include
#include
#define N 100005
#define M 1000005
#define inf 1ll<<31ll-1
using namespace std;
int n, m, s, t, ss, tt, num = 1;
int v[M], w[M], next1[M];
int d[N], f[N], sum[N], first[N];
bool can[N];
void add(int x, int y, int f)
{
     
	num++;
	next1[num] = first[x];
	first[x] = num;
	v[num] = y;
	w[num] = f;
}
bool bfs(int start, int end)
{
     
	int x, y, i, j;
	memset(d, -1, sizeof(d));
	memcpy(f, first, sizeof(f));
	queue<int>q;
	q.push(start);
	d[start] = 0;
	while (!q.empty())
	{
     
		x = q.front();
		q.pop();
		for (i = first[x]; i; i = next1[i])
		{
     
			y = v[i];
			if (w[i] && d[y] == -1 && !can[y])
			{
     
				d[y] = d[x] + 1;
				if (y == end)
					return true;
				q.push(y);
			}
		}
	}
	return false;
}
int dinic(int now, int end, int flow)
{
     
	if (now == end)
		return flow;
	int x, delta, ans = 0;
	for (int& i = f[now]; i; i = next1[i])
	{
     
		x = v[i];
		if (w[i] && d[x] == d[now] + 1 && !can[x])
		{
     
			delta = dinic(x, end, min(flow, w[i]));
			w[i] -= delta;
			w[i ^ 1] += delta;
			flow -= delta;
			ans += delta;
			if (!flow)  break;
		}
	}
	if (flow)  d[now] = -1;
	return ans;
}
int main()
{
     
	int x, y, i, j, l, r;
	int ans = 0, maxflow = 0;
	scanf("%d%d%d%d", &n, &m, &s, &t);
	ss = 0, tt = n + 1;
	for (i = 1; i <= m; ++i)
	{
     
		scanf("%d%d%d%d", &x, &y, &l, &r);
		sum[x] -= l, sum[y] += l;
		add(x, y, r - l), add(y, x, 0);
	}
	for (i = 1; i <= n; ++i)
	{
     
		if (sum[i] > 0)  add(ss, i, sum[i]), add(i, ss, 0), ans += sum[i];
		if (sum[i] < 0)  add(i, tt, -sum[i]), add(tt, i, 0);
	}
	add(t, s, inf), add(s, t, 0);
	while (bfs(ss, tt))
		maxflow += dinic(ss, tt, inf);
	can[ss] = false;
	can[tt] = false;
	if (maxflow != ans)
	{
     
		printf("please go home to sleep");
		return 0;
	}
	maxflow = 0;
	while (bfs(s, t))
		maxflow += dinic(s, t, inf);
	printf("%d", maxflow);
	return 0;
}

最短路径

dijkstra(更新于2021/1/6)

#include
#include
#include
#define MAX 200020
#define inf 0x7fffffff
using namespace std;
int n, m,vis[MAX];
long long dis[MAX];
struct edgenode
{
     
	int to;
	int next;
	int weight;
}edge[MAX];
int  cnt, head[MAX];
int u, v, w;
int s;
struct node
{
     
	long long dis;
	int pos;
	bool operator <(const node& x)const
	{
     
		return x.dis < dis;
	}
};
std::priority_queue<node> q;//优先队列
void add_edge(int u, int v, int w);
void dijkstra();
int main()
{
     
	memset(dis, -1, sizeof(dis));
	scanf_s("%d%d%d", &n, &m, &s);
	for (int i = 1; i <= n; i++)dis[i] = inf;
	for (int i = 0; i < m; i++)
	{
     
		scanf_s("%d%d%d", &u, &v, &w);
		add_edge(u, v, w);
	}
	dijkstra();
	for (int i = 1; i <= n; i++)printf("%lld ", dis[i]);
}
void add_edge(int u, int v, int w)
{
     
	edge[++cnt] = edgenode{
      v,head[u],w };
	head[u] = cnt;
}
void dijkstra()
{
     
	dis[s] = 0;
	q.push(node {
      0, s });
	while (!q.empty())
	{
     
		node tmp = q.top();
		q.pop();
		int x = tmp.pos, d = tmp.dis;
		if (vis[x])
			continue;
		vis[x] = 1;
		for (int i = head[x]; i; i = edge[i].next)
		{
     
			int y = edge[i].to;
			if (dis[y] > dis[x] + edge[i].weight)
			{
     
				dis[y] = dis[x] + edge[i].weight;
				if (!vis[y])
				{
     
					q.push(node {
      dis[y], y });
				}
			}
		}
	}
}

spfa(更新于2021/1/6)

#include
#include
#include
#define MAX 200010
#define inf 2147483647
using namespace std;
int n, m, s;//点数,边数,出发点
int vis[MAX];
long long dis[MAX];
int head[MAX], cnt, u, v, w;
struct node
{
     
	int to;
	int next;
	int weight;
}edge[MAX];
void add_edge(int u, int v, int w);
void spfa();
int main()
{
     
	memset(head, -1, sizeof(head));
	scanf_s("%d%d%d", &n, &m, &s);
	for (int i = 0; i < m; i++)
	{
     
		scanf_s("%d%d%d", &u, &v, &w);
		add_edge(u, v, w);
	}
	spfa();
	for (int i = 1; i <= n; i++)
		if (i == s)printf("0 ");
		else printf("%lld ", dis[i]);

}
void add_edge(int u, int v, int w)
{
     
	edge[++cnt] = node{
      v,head[u],w };
	head[u] = cnt;
}
void spfa()
{
     
	queue<int> q; //spfa用队列,这里用了STL的标准队列
	for (int i = 1; i <= n; i++)
	{
     
		dis[i] = inf; //带权图初始化
		vis[i] = 0; //记录点i是否在队列中,同dijkstra算法中的visited数组
	}
	q.push(s); dis[s] = 0; vis[s] = 1; //第一个顶点入队,进行标记
	while (!q.empty())
	{
     
		int u = q.front(); //取出队首
		q.pop(); vis[u] = 0; //出队标记
		for (int i = head[u]; i!=-1; i = edge[i].next) //邻接表遍历7
		{
     
			int v = edge[i].to;
			if (dis[v] > dis[u] + edge[i].weight) //如果有最短路就更改
			{
     
				dis[v] = dis[u] + edge[i].weight;
				if (vis[v] == 0) //未入队则入队
				{
     
					vis[v] = 1; //标记入队
					q.push(v);
				}
			}
		}
	}
}

最小生成树

kruskal(更新于2021/1/6)

#include
#include
#include
using namespace std;

#define MAXN 11		//顶点个数的最大值
#define MAXM 20		//边的个数的最大值
struct edge			//边
{
     
	int u, v, w;
}edges[MAXM];		//边的数组
int parent[MAXN];	//parent[i]为顶点i所在集合对应的树中的根结点
int n, m;			//顶点个数、边的个数
int i, j;			//循环变量
void UFset()		//初始化 
{
     
	for (i = 1; i <= n; i++) parent[i] = -1;
}
int Find(int x)		//查找并返回结点x所属集合的根结点
{
     
	int s;			//查找位置
	for (s = x; parent[s] >= 0; s = parent[s]);
	while (s != x)	//优化方案——压缩路径,使后续的查找操作加速
	{
     
		int tmp = parent[x];
		parent[x] = s;
		x = tmp;
	}
	return s;
}
//运用并查集,将两个不同集合的元素进行合并,使两个集合中任意两个元素都连通
void Union(int R1, int R2)
{
     
	int r1 = Find(R1), r2 = Find(R2);		//r1和r2分别为R1和R2的根结点
	int tmp = parent[r1] + parent[r2];		//两个集合结点数之和(负数)
	//如果R2所在树结点个数 > R1所在树结点个数(注意parent[r1]是负数)
	if (parent[r1] > parent[r2])
	{
     
		parent[r1] = r2;
		parent[r2] = tmp;
	}
	else
	{
     
		parent[r2] = r1;
		parent[r1] = tmp;
	}
}
int cmp(const void* a, const void* b)		//实现从小到大的比较函数
{
     
	edge aa = *(const edge*)a, bb = *(const edge*)b;
	return aa.w - bb.w;
}
void Kruskal()
{
     
	int sumweight = 0;		//生成树的权值
	int num = 0;			//已选用的边的数目
	UFset();				//初始化parent数组
	for (i = 0; i < m; i++)
	{
     
		if (Find(edges[i].u) != Find(edges[i].v))
		{
     
			printf("%d %d %d\n", edges[i].u, edges[i].v, edges[i].w);
			sumweight += edges[i].w; num++;
			Union(edges[i].u, edges[i].v);
		}
		if (num >= n - 1) break;
	}
	printf("The weight of MST is : %d\n", sumweight);
}
void main()
{
     
	scanf("%d%d", &n, &m);	//读入顶点个数和边数
	for (int i = 0; i < m; i++)
		scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].w);	//读入边的起点和终点
	printf("The edges chosen are :\n");
	qsort(edges, m, sizeof(edges[0]), cmp);	//对边按权值从小到大排序
	Kruskal();
}

prim(更新于2021/1/6)

#include
#include
#include
#include
#include
using namespace std;
#define INF 0x3f3f3f3f
#define MAXN 110
int map[MAXN][MAXN], lowcost[MAXN];
bool visit[MAXN];
int nodenum, sum;

void prim()
{
     
	int temp, k;
	sum = 0;
	memset(visit, false, sizeof(visit)); //初始化visit
	visit[1] = true;
	for (int i = 1; i <= nodenum; ++i) //初始化lowcost[i]
		lowcost[i] = map[1][i];
	for (int i = 1; i <= nodenum; ++i)//找生成树集合点集相连最小权值的边
	{
     
		temp = INF;
		for (int j = 1; j <= nodenum; ++j)
			if (!visit[j] && temp > lowcost[j])
				temp = lowcost[k = j];
		if (temp == INF) break;
		visit[k] = true; //加入最小生成树集合
		sum += temp;//记录权值之和
		for (int j = 1; j <= nodenum; ++j) //更新lowcost数组
			if (!visit[j] && lowcost[j] > map[k][j])
				lowcost[j] = map[k][j];
	}
}

int main()
{
     
	int a, b, cost, edgenum;
	while (scanf("%d", &nodenum) && nodenum)//结点数
	{
     
		memset(map, INF, sizeof(map));
		edgenum = nodenum * (nodenum - 1) / 2;
		for (int i = 1; i <= edgenum; ++i) //输入边的信息
		{
     
			scanf("%d%d%d", &a, &b, &cost);
			if (cost < map[a][b])
				map[a][b] = map[b][a] = cost;
		}
		prim();
		printf("%d\n", sum); //最小生成树权值之和
	}
	return 0;
}

欧拉通路与欧拉回路

并查集(更新于2021/1/6)

#include 
#include
using namespace std;
const int maxn = 10002;
int n, m, a[maxn];
int Chaxun(int x)
{
     
    return (a[x] == x) ? x : a[x] = Chaxun(a[x]);
}

void Hebin(int x, int y)
{
     
    a[Chaxun(x)] = Chaxun(y);
}
int main()
{
     
    int i, x, y, z;
    scanf("%d%d", &n, &m);
    for (i = 1; i <= n; i++)a[i] = i;
    for (i = 0; i < m; i++)
    {
     
        scanf("%d%d%d", &z, &x, &y);
        if (z == 1)Hebin(x, y);
        if (z == 2)
        {
     
            if (Chaxun(x) == Chaxun(y))printf("Y\n");
            else printf("N\n");
        }
    }
    return 0;
}

判断存在欧拉回路(更新于2021/1/6)

#include 

int arr[1000];
int father[1000];
int rand_deep[1000];

int findSet(int x) {
     
	int px = x, i;
	while (px != father[px])
		px = father[px];
	//路径压缩,加快查找速度
	while (x != px) {
     
		i = father[x];
		father[x] = px;
		x = i;
	}
	return px;
}

void unionSet(int x, int y) {
     
	x = findSet(x);
	y = findSet(y);
	if (rand_deep[x] > rand_deep[y])
		father[y] = x;
	else {
     
		father[x] = y;
		if (rand_deep[x] == rand_deep[y])rand_deep[y]++;
	}
}
//并查集
int main() {
     
	int N, M;
	while (scanf("%d", &N) != EOF && N) {
     
		scanf("%d", &M);
		int i;
		int flag = 1;
		for (i = 1; i <= N; i++) {
     
			father[i] = i;
			rand_deep[i] = 0;
			arr[i] = 0;
		}
		for (i = 0; i < M; i++) {
     
			int x, y;
			scanf("%d %d", &x, &y);
			arr[x] ++;
			arr[y] ++;
			unionSet(x, y);
		}

		int father;
		for (i = 1; i <= N; i++) {
     
			if (i == 1)
				father = findSet(1);
			else {
     
				if (father != findSet(i)) {
     
					flag = 0;
					break;
				}
			}
			if (arr[i] == 0 || arr[i] % 2 != 0) {
     
				flag = 0;
				break;
			}
		}
		//判断是否在同一连通分量中
		printf("%d\n", flag);

	}
	return 0;
}


寻找欧拉路径(更新于2021/1/6)

#include
#include
#include
#include
#include
#include
using namespace std;

const int N = 1005;
int n, m, flag, top, sum, du[N], ans[5005], map[N][N];

void dfs(int x)
{
     
    ans[++top] = x;
    for (int i = 1; i <= n; i++)
    {
     
        if (map[x][i] >= 1)
        {
     
            map[x][i]--;
            map[i][x]--;
            dfs(i);
            break;
        }
    }
}

void fleury(int x)
{
     
    top = 1;
    ans[top] = x;
    while (top > 0)
    {
     
        int k = 0;
        for (int i = 1; i <= n; i++)//判断是否可扩展
        {
     
            if (map[ans[top]][i] >= 1)//若存在一条从ans[top]出发的边  那么就是可扩展
            {
     
                k = 1; break;
            }
        }
        if (k == 0)//该点x没有其他的边可以先走了(即不可扩展), 那么就输出它
        {
     
            printf("%d ", ans[top]);
            top--;
        }
        else if (k == 1)//如可扩展, 则dfs可扩展的哪条路线
        {
     
            top--;//这需要注意
            dfs(ans[top + 1]);
        }
    }
}
int main()
{
     
    while (scanf("%d%d", &n, &m) != EOF)
    {
     
        memset(du, 0, sizeof(du));
        memset(map, 0, sizeof(map));

        for (int i = 1; i <= m; i++)
        {
     
            int x, y;
            scanf("%d%d", &x, &y);
            map[x][y]++; //记录边, 因为是无向图所以加两条边, 两个点之间可能有多条边
            map[y][x]++;
            du[x]++;
            du[y]++;
        }
        flag = 1; // flag标记开始点。 如果所有点度数全为偶数那就从1开始搜
        sum = 0;
        for (int i = 1; i <= n; i++)
        {
     
            if (du[i] % 2 == 1)
            {
     
                sum++;
                flag = i;// 若有奇数边, 从奇数边开始搜
            }
        }
        if (sum == 0 || sum == 2)//度数均为偶数或仅有两个奇度定点则开始算法
            fleury(flag);
    }
    return 0;
}

prufer编码

prufer编码转树(更新于2021/1/6)

#include
#include
#include
#include
using namespace std;
#define MAX 20//顶点数最大值
typedef struct arc
{
     
	int u;
	int v;
}arcnode;
queue<int> q1;
int flag[MAX];
int n, m, edgenum;
int min();
int main()
{
     
	arcnode edge[MAX * (MAX - 1) / 2];//边集
	scanf_s("%d", &n);//顶点数
	for (int i = 0; i < n - 2; i++)
	{
     
		scanf_s("%d", &m);
		q1.push(m);
		flag[m]++;
	}
	q1.push(n);
	flag[n]++;
	while(!q1.empty())
	{
     
		int u = min();
		flag[u]++;
		int v = q1.front();
		q1.pop();
		flag[v]--;
		edge[edgenum].u = u;
		edge[edgenum].v = v;
		edgenum++;
	}
	for (int i = 0; i < edgenum; i++)
	{
     
		printf("(%d,%d)\n", edge[i].u, edge[i].v);
	}
	return 0;
}
int min()//求不在队列内的点编号最小值
{
     
	for (int i = 1; i <= n; i++)
	{
     
		if (flag[i] == 0)return i;
	}
}

LCA(更新于2021/1/6)

#include
#include
#define MAX 600000
using namespace std;
int n, m, s;//树节点个数,询问个数,根节点序号
int x, y;//查询点序号
int father[MAX][20], log_2[MAX], depth[MAX],lca[MAX];//father[i][j]表示节点i的第2^j级祖先
struct node
{
     
	int to;
	int next;
}edge[2*MAX];
int cnt, u, v, head[MAX];
void add_edge(int u, int v);
void dfs(int present_node, int father_node);
int LCA(int x, int y);//求点x和y的最近公共祖先
int main()
{
     
	memset(head, -1, sizeof(head));
	scanf_s("%d%d%d", &n, &m, &s);//树节点个数,询问个数,根节点序号
	for (int i = 0; i < n - 1; i++)
	{
     
		scanf_s("%d%d", &u, &v);
		add_edge(u, v); add_edge(v, u);
	}
	for (int i = 1; i <= n; ++i) //预先算出log_2(i)+1的值
		log_2[i] = log_2[i - 1] + (1 << log_2[i - 1] == i);
	dfs(s, 0);
	for (int i = 0; i < m; i++)
	{
     
		scanf_s("%d%d", &x, &y);
		lca[i] = LCA(x, y);	
	}
	for (int i = 0; i < m;i++)printf("%d\n", LCA(x, y));
	return 0;
}
void add_edge(int u, int v)
{
     
	edge[++cnt] = node{
      v,head[u] };
	head[u] = cnt;
}
void dfs(int present_node, int father_node)
{
     
	father[present_node][0] = father_node;
	depth[present_node] = depth[father_node] + 1;
	for (int i = 1; i <= log_2[depth[present_node]]; i++)
	{
     
		father[present_node][i] = father[father[present_node][i - 1]][i - 1];
	}//当前节点的2^i祖先等于当前节点的2^(i-1)级祖先的2^(i-1)级祖先即2^i=2^(i+1)+2^(i+1)
	for (int i = head[present_node]; i; i = edge[i].next)
	{
     
		if (edge[i].to != father_node)
			dfs(edge[i].to, present_node);
	}
}
int LCA(int x, int y)
{
     
	if (depth[x] < depth[y])
		swap(x, y);//不妨x的深度大于y的深度
	while (depth[x] > depth[y])
		x = father[x][log_2[depth[x] - depth[y]] - 1];//将x跳到与y同深度
	if (x == y)return x;
	for (int k = log_2[depth[x]] - 1; k >= 0; --k) //不断向上跳
	{
     
		if (father[x][k] != father[y][k])  //因为我们要跳到它们LCA的下面一层,所以它们肯定不相等,如果不相等就跳过去。
			x = father[x][k], y = father[y][k];
	}
	return father[x][0];  //返回父节点
}

tarjan求割点(更新于2021/1/6)

#include
#include
#include
#include
#define MAX 20100
using namespace std;
int n, m, index1, cutnum;
int LOW[MAX], cut_vex[MAX], DFN[MAX];
struct node
{
     
	int to;
	int next;
}edge[MAX * 10];
int u, v;
int head[MAX], cnt;
void add_edge(int u, int v);
void tarjan(int u, int fa);
int main()
{
     
	memset(DFN, 0, sizeof(DFN));
	memset(head, -1, sizeof(head));
	scanf("%d%d", &n, &m);
	for (int i = 0; i < m; i++)
	{
     
		scanf("%d%d", &u, &v);
		add_edge(u, v);
		add_edge(v, u);
	}
	for (int i = 1; i <= n; i++)
	{
     
		if (DFN[i] == 0)
			tarjan(i, i);
	}
	for (int i = 1; i <= n; i++)
	{
     
		if (cut_vex[i])
			cutnum++;
	}
	printf("%d\n", cutnum);
	for (int i = 1; i <= n; i++)
	{
     
		if (cut_vex[i])
			printf("%d ", i);
	}
}
void add_edge(int u, int v)
{
     
	edge[++cnt].to = v;
	edge[cnt].next = head[u];
	head[u] = cnt;
}
void tarjan(int u, int fa)//当前节点及其父节点
{
     
	index1++;
	DFN[u] = index1;
	LOW[u] = index1;//index记录遍历的点的个数,当前节点的DFN和LOW均为查询顺序
	int child = 0;
	for (int i = head[u]; i != -1; i = edge[i].next)//遍历当前节点的所有子节点
	{
     
		int nx = edge[i].to;
		if (!DFN[nx])//若该子节点未访问则求出其所在连通分量
		{
     
			tarjan(nx, fa);
			LOW[u] = min(LOW[u], LOW[nx]);//更新当前节点的最近根节点
			if (LOW[nx] >= DFN[u] && u != fa)//
				cut_vex[u] = 1;
			if (u == fa)
				child++;
		}
		LOW[u] = min(LOW[u], DFN[nx]);
	}
	if (child >= 2 && u == fa)
		cut_vex[u] = 1;
}

你可能感兴趣的:(图论,算法)