例题:
欧拉回路
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 17034 Accepted Submission(s): 6579
Problem Description
欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结
束。
束。
Output
每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
Sample Input
3 31 21 32 33 21 22 30
Sample Output
10
Author
ZJU
Source
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
int n,m,u,v,flag;
int degree[1005];
vector<int> G[1005];
int bfs()
{
int vis[1005],cnt=0;
memset(vis,0,sizeof(vis));
queue<int> q;
q.push(1); vis[1]=1;
while(!q.empty())
{
int v=q.front(); q.pop();
cnt++;
//cout << v << endl;
for (int t=0;t<G[v].size();t++)
{
if (!vis[G[v][t]])
{
q.push(G[v][t]);
vis[G[v][t]]=1;
}
}
}
//cout << cnt << endl;
if (cnt==n) return 1;
else return 0;
}
int main()
{
while(cin >> n && n)
{
for (int i=1;i<=n;i++)
G[i].clear();
flag=1;
memset(degree,0,sizeof(degree));
cin >> m;
for (int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
degree[u]++; //u的入度加一
degree[v]++; //v的入度加一
}
for (int i=1;i<=n;i++) //判断入度是否都为偶数
if (degree[i]%2)
{
flag=0;
break;
}
if (flag&&bfs()) //利用bfs判断是否为连通图
printf("1\n");
else
printf("0\n");
}
return 0;
}
1. 连通图
2. 有向图:所有定点入度等于出度
无向图:度为偶数
判断连通图可以用bfs,dfs也可以用warshall(不会)。