演算法思路:並查集,判斷連通並且無環,只有一個0入度頂點。
無環條件:邊數 + 1 = 頂點數。
連通條件:只有1個或者0個(迴路)頂點滿足 next_node[j] == j && flag[j] != 0。
//模板開始#include <string> #include <vector> #include <algorithm> #include <iostream> #include <sstream> #include <fstream> #include <map> #include <set> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime>#include<iomanip>#include<string.h>#define SZ(x) (int(x.size()))using namespace std;int toInt(string s){istringstream sin(s); int t; sin>>t; return t;}template<class T> string toString(T x){ostringstream sout; sout<<x; return sout.str();}typedef long long int64;int64 toInt64(string s){istringstream sin(s); int64 t; sin>>t;return t;}template<class T> T gcd(T a, T b){ if(a<0) return gcd(-a, b);if(b<0) return gcd(a, -b);return (b == 0)? a : gcd(b, a % b);}//模板結束(通用部分)#define ifs cinint findset(int x, int pa[]){return pa[x] != x ? pa[x] = findset(pa[x], pa) : x;}//【圖論05】並查集 1003 Is It A Tree?#define MAX_SIZE 100005int next_node[MAX_SIZE];//儲存有向圖的邊int in[MAX_SIZE];//儲存節點的入度int out[MAX_SIZE];//儲存節點的出度int flag[MAX_SIZE];//標記節點是否存在void init()//初始化{for(int i = 0; i < MAX_SIZE; i++){next_node[i] = i;}memset(in, 0, sizeof(in));memset(out, 0, sizeof(out));memset(flag, 0, sizeof(flag));}int findset(int a)//找元素所在集合的代表元(因為用了路徑壓縮,路徑壓縮的主要目的是為了儘快的確定元素所在的集合){while(next_node[a] != a){a = next_node[a];}return a;}void union_nodes(int a, int b)//集合合并{int a1 = findset(a);int b1 = findset(b);next_node[a1] = b1;}int main(){//ifstream ifs("shuju.txt", ios::in);int m, n;int cases = 0;while(ifs>>m>>n && !(m < 0 && n < 0)){cases++;if(m == 0 && n == 0){cout<<"Case "<<cases<<" is a tree."<<endl;continue;}int bianshu = 0;init();bianshu++;union_nodes(m, n);out[m]++;in[n]++;flag[m]++;flag[n]++;while(ifs>>m>>n && !(m == 0 && n == 0))//輸入資料,建立有向圖,併合並相關集合{//int a = data[0] - 'a';//int b = data[strlen(data) - 1] - 'a';bianshu++;union_nodes(m, n);out[m]++;in[n]++;flag[m]++;flag[n]++;}int count = 0;for(int j = 0; j < MAX_SIZE; j++)//計算有向圖中連通分支的個數{if(next_node[j] == j && flag[j] != 0){count++;}}int root = 0;for(int j = 0; j < MAX_SIZE; j++){if(in[j] == 0 && flag[j] != 0){root++;}}if(root >= 2){cout<<"Case "<<cases<<" is not a tree."<<endl;continue;}int jiedianshu = 0;for(int j = 0; j < MAX_SIZE; j++){if(flag[j] != 0){jiedianshu++;}}if(jiedianshu == 1){cout<<"Case "<<cases<<" is not a tree."<<endl;}if(count == 1 && jiedianshu == bianshu + 1){cout<<"Case "<<cases<<" is a tree."<<endl;}else{cout<<"Case "<<cases<<" is not a tree."<<endl;}}return 0;}