【解析】案例4-1.7 文件传输 (25 分)
立志用最少的代碼做最高效的表達
當兩臺計算機雙向連通的時候,文件是可以在兩臺機器間傳輸的。給定一套計算機網絡,請你判斷任意兩臺指定的計算機之間能否傳輸文件?
輸入格式:
首先在第一行給出網絡中計算機的總數 N (2≤N≤10^4),于是我們假設這些計算機從 1 到 N 編號。隨后每行輸入按以下格式給出:
I c1 c2
其中I表示在計算機c1和c2之間加入連線,使它們連通;或者是
C c1 c2
其中C表示查詢計算機c1和c2之間能否傳輸文件;又或者是
S
這里S表示輸入終止。
輸出格式:
對每個C開頭的查詢,如果c1和c2之間可以傳輸文件,就在一行中輸出"yes",否則輸出"no"。當讀到終止符時,在一行中輸出"The network is connected.“如果網絡中所有計算機之間都能傳輸文件;或者輸出"There are k components.”,其中k是網絡中連通集的個數。
輸入樣例 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S
輸出樣例 1:
no
no
yes
There are 2 components.
輸入樣例 2:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
S
輸出樣例 2:
no
no
yes
yes
The network is connected.
暴力使用DFS必定超時。 并查集模板題
#include<iostream> #include<cstdio> #include<string> using namespace std; const int maxn = 1e4 + 5; int pre[maxn]; //定義并查集數組 int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); }void merge(int x,int y){int fx=find(x);int fy=find(y);if(fx > fy) pre[fx] = fy;else pre[fy] = fx; }int main() {int n, x, y;char c; cin >> n;getchar();for(int i = 1; i <= n; i++) pre[i] = i; //1、初始化 while(cin >> c) {if(c == 'S') { //判斷連通塊 int ans = 0; for(int i = 1; i <= n; i++) {if(i == pre[i]) ans++; //如果是這樣,說明是單獨節點 }if(ans == 1) printf("The network is connected.\n");else printf("There are %d components.\n", ans);break;} else if(c == 'I') {scanf("%d%d", &x, &y);getchar();merge(x, y);} else if(c == 'C') {scanf("%d%d", &x, &y);getchar();if(find(x) == find(y)) printf("yes\n");else printf("no\n");}}return 0; }
耗時
?????????——泰山崩于前而色不變,麋鹿興于左而目不瞬。
總結
以上是生活随笔為你收集整理的【解析】案例4-1.7 文件传输 (25 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 案例4-1.6 树种统计 (25 分)_
- 下一篇: 【视频讲解】基础实验4-2.1 树的同构