歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條迴路。現給定一個圖,問是否存在歐拉回路?
輸入:
測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是節點數N ( 1 < N < 1000 )和邊數M;隨後的M行對應M條邊,每行給出一對正整數,分別是該條邊直接連通的兩個節點的編號(節點從1到N編號)。當N爲0時輸入結束。
輸出:
每個測試用例的輸出佔一行,若歐拉回路存在則輸出1,否則輸出0。
樣例輸入:
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
樣例輸出:
1
0
判斷歐拉回路,首先圖得連通,然後每個點的入度和出度和是偶數。
DFS方法:
#include <iostream>
using namespace std;
const int MaxInt = 9999;
const int MaxNum = 1000;
bool c[MaxNum][MaxNum];
bool visited[MaxNum];
int calc[MaxNum];
void DFS(int i, int N, int &count)
{
count++;
visited[i] = true;
for(int j = 1; j <= N; ++j)
{
if(!visited[j] && c[i][j] < MaxInt)
DFS(j,N,count);
}
}
bool Judge(int N)
{
for(int i = 1; i <= N; ++i)
{
if(calc[i] % 2)
return false;
}
return true;
}
int main()
{
int N,M;
while(cin >> N)
{
if(N == 0)
break;
cin >> M;
for(int i = 1; i <= N; ++i)
{
for(int j = 1; j <= N; ++j)
{
c[i][j] = false;
}
}
for(int i = 1; i <= N; ++i)
calc[i] = 0;
for(int i = 1; i <= M; ++i)
{
int p,q;
cin >> p >> q;
c[p][q] = true;
c[q][p] = true;
calc[p]++;
calc[q]++;
}
for(int i = 1; i <= N; ++i)
visited[i] = false;
int count = 0;
DFS(1,N,count);
if(count != N)
cout << 0 << endl;
else
{
if(Judge(N))
cout << 1 << endl;
else
cout << 0 << endl;
}
}
return 0;
}
並查集:
#include <iostream>
#include <vector>
using namespace std;
const int MaxInt = 9999;
const int MaxNum = 1000;
bool c[MaxNum][MaxNum];
int calc[MaxNum];
int find(vector<int> &a, int x)
{
if(a[x] < 0)
return x;
else
return a[x] = find(a,a[x]);
}
void unionSets(vector<int> &a, int root1,int root2)
{
int b = find(a,root1);
int c = find(a,root2);
if(b == c)
return;
if(a[b] < a[c])
{
a[b] += a[c];
a[c] = b;
}
else
{
a[c] += a[b];
a[b] = c;
}
}
bool Judge(int N)
{
for(int i = 1; i <= N; ++i)
{
if(calc[i] % 2)
return false;
}
return true;
}
int main()
{
int N,M;
vector<int> ivec;
while(cin >> N)
{
if(N == 0)
break;
cin >> M;
ivec.assign(N + 1,-1);
for(int i = 1; i <= N; ++i)
{
for(int j = 1; j <= N; ++j)
{
c[i][j] = false;
}
}
for(int i = 1; i <= N; ++i)
calc[i] = 0;
for(int i = 1; i <= M; ++i)
{
int p,q;
cin >> p >> q;
c[p][q] = true;
c[q][p] = true;
unionSets(ivec,p,q);
calc[p]++;
calc[q]++;
}
int count = 0;
for(int i = 1; i <= N; ++i)
{
if(find(ivec,i) == i)
count++;
}
if(count != 1)
cout << 0 << endl;
else
{
if(Judge(N))
cout << 1 << endl;
else
cout << 0 << endl;
}
ivec.clear();
}
return 0;
}