描述:有n(n<=100)個人,每個人有一個或多個朋友(朋友關係是相互的)。將其分成兩組,使每一組都有朋友在另一個組。
#include <cstdio>#include <iostream>#include <cstring>#include <vector>using namespace std;const int M = 100 + 10;int color[M], vis[M];//color[i]表示結點i的顏色,1表示黑色,2白色vector<int> G[M];void dfs(int u){vis[u] = 1;for (int i = 0; i < G[u].size(); ++i){int v = G[u][i];if (!vis[v]){color[v] = 3 - color[u];dfs(v);}}}int main(){int n, t;scanf("%d", &n);for (int i = 1; i <= n; ++i)while (scanf("%d", &t) && t){G[i].push_back(t);}memset(vis, 0, sizeof(vis));memset(color, 0, sizeof(color));for (int i = 1; i <= n; ++i)if (!vis[i]){color[i]=1;//每個新連通分量起始點都要設定為1dfs(i);}int sum = 0;for (int i = 1; i <= n; ++i)if (color[i] == 1)++sum;printf("%d\n", sum);for (int i = 1; i <= n; ++i)if (color[i] == 1)printf("%d ", i);return 0;}
還有一種方法差不多,看著像dfs實際不是,本題只需要對每個結點的鄰接點染色就行,可以不用遞迴。
#include <cstdio>#include <iostream>#include <cstring>#include <vector>using namespace std;const int M = 100 + 10;int color[M], vis[M];vector<int> G[M];void coloring(int u){vis[u] = 1;color[u] = 1;for (int i = 0; i < G[u].size(); ++i){int v = G[u][i];if (!vis[v])color[v] = 3 - color[u];vis[v] = 1;}}int main(){int n, t;scanf("%d", &n);for (int i = 1; i <= n; ++i)while (scanf("%d", &t) && t){G[i].push_back(t);}memset(vis, 0, sizeof(vis));memset(color, 0, sizeof(color));for (int i = 1; i <= n; ++i)if (!vis[i])coloring(i);int sum = 0;for (int i = 1; i <= n; ++i)if (color[i] == 1)++sum;printf("%d\n", sum);for (int i = 1; i <= n; ++i)if (color[i] == 1)printf("%d ", i);return 0;}