标签:数据 logs php 结束 targe output 相同 ble 初始
畅通工程
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 int n, m; 5 int G[1005][1005]; 6 int vis[1005]; //标记数组 7 int is[1005]; //有道路连接的点 8 9 void dfs(int u){ 10 if(vis[u]) return; //被访问过就进行回溯 11 vis[u] = 1; //标记 12 for(int i = 1; i <= 1000; i++){ 13 if(G[u][i]) dfs(i); 14 } 15 } 16 17 int main(){ 18 int u, v; 19 while(~scanf("%d", &n) && n){ 20 scanf("%d", &m); 21 memset(G, 0, sizeof(G)); 22 memset(vis, 0, sizeof(vis)); 23 memset(is, 0, sizeof(is)); 24 25 for(int i = 0; i < m; i++){ 26 scanf("%d%d", &u, &v); 27 G[u][v] = G[v][u] = 1; //双向的路 28 is[u] = is[v] = 1; 29 } 30 31 int cnt = 0; //计数 32 for(int i = 1; i <= n; i++){ 33 if(is[i] && !vis[i]){ //有道路连接并且没被访问过 34 dfs(i); //进行搜索 35 cnt++; 36 } 37 } 38 39 for(int i = 1; i <= n; i++){ 40 if(!vis[i]) cnt++; //统计独立的点 41 } 42 43 printf("%d\n", cnt-1); 44 } 45 return 0; 46 }
1 #include <cstdio> 2 #include <cstring> 3 #include <vector> 4 using namespace std; 5 int n, m; 6 vector<int> G[1005]; //邻接表 7 int vis[1005]; //标记数组 8 int is[1005]; //有道路连接的点 9 10 void dfs(int u){ 11 if(vis[u]) return; //被访问过就进行回溯 12 vis[u] = 1; //标记 13 for(int i = 0; i < G[u].size(); i++) dfs(G[u][i]); 14 } 15 16 int main(){ 17 int u, v; 18 while(~scanf("%d", &n) && n){ 19 scanf("%d", &m); 20 for(int i = 0; i < 1005; i++){ 21 G[i].clear(); 22 } 23 memset(vis, 0, sizeof(vis)); 24 memset(is, 0, sizeof(is)); 25 26 for(int i = 0; i < m; i++){ 27 scanf("%d%d", &u, &v); 28 G[u].push_back(v); 29 G[v].push_back(u); //双向的路 30 is[u] = is[v] = 1; 31 } 32 33 int cnt = 0; //计数 34 for(int i = 1; i <= n; i++){ 35 if(is[i] && !vis[i]){ //有道路连接并且没被访问过 36 dfs(i); //进行搜索 37 cnt++; 38 } 39 } 40 41 for(int i = 1; i <= n; i++){ 42 if(!vis[i]) cnt++; //统计独立的点 43 } 44 45 printf("%d\n", cnt-1); 46 } 47 return 0; 48 }
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 int road[1005]; 5 6 int fd(int u){ 7 int r = u; 8 while(road[r] != r){ 9 r = road[r]; //查 10 } 11 12 int i = u; 13 int next; 14 while(i != r){ //状态压缩 15 next = road[i]; 16 road[i] = r; 17 i = next; 18 } 19 return r; 20 } 21 22 int main(){ 23 int n; 24 while(scanf("%d", &n) == 1 && n){ 25 int m; 26 scanf("%d", &m); 27 memset(road, 0, sizeof(road)); 28 for(int i = 1; i <= n; i++){ 29 road[i] = i; //初始化并查集数组 30 } 31 32 int a, b; 33 int a1, b1; 34 while(m--){ 35 scanf("%d%d", &a, &b); 36 a1 = fd(a); //查 37 b1 = fd(b); 38 if(a1 != b1){ //不属于同一个集合就并 39 road[a1] = b1; 40 } 41 } 42 43 int cnt = 0; 44 for(int i = 1; i <= n; i++){ 45 if(road[i] == i) cnt++; 46 } 47 48 printf("%d\n", cnt-1); 49 } 50 return 0; 51 }
标签:数据 logs php 结束 targe output 相同 ble 初始
原文地址:https://www.cnblogs.com/happy-MEdge/p/10505315.html