日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【解析】1013 Battle Over Cities (25 分)_31行代码AC

發布時間:2024/2/28 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【解析】1013 Battle Over Cities (25 分)_31行代码AC 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優題解——>傳送門


It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.
I
For example, if we have 3 cities and 2 highways connecting city?1??-city?2?? and city?1??-city?3??. Then if city?1?? is occupied by the enemy, we must have 1 highway repaired, that is the highway city?2??-city?3??.

IInput Specification:
Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

IOutput Specification:
For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

ISample Input:
3 2 3
1 2
1 3
1 2 3

Sample Output:
1
0
0


題意:n座城,m條路,k個淪陷的城市, 要求每個城市之間都要有通信, 求某城市淪陷后至少修幾條路才能達到要求。

分析:經典連通塊問題。 計算城市網中有多少連通塊,連通塊個數-1就是要修的道路數(連通塊彼此相連,則所有城市相連)。

解法:DFS解法與拓撲排序解法皆可。 先寫了DFS解法,拓撲排序解法明天更新~

注意:如果用cin、cout輸出,最好加上ios::sync_with_stdio(false);這句代碼,可以減少大概100ms的時間規模(比scanf、printf還快)。

關閉流同步前:

關閉流同步后:


代碼一:DFS解法

#include<bits/stdc++.h> using namespace std;int n, m, k, lost_city, G[1010][1010], vis[1010];void dfs(int u) {for(int v = 1; v <= n; v++) if(G[u][v] == 1 && vis[v] == 0 && v != lost_city) {vis[v] = 1;dfs(v); // vis[v] = 0; 求連通塊時無回溯 } }int main() {ios::sync_with_stdio(false);cin >> n >> m >> k;for(int i = 0; i < m; i++) {int a, b; cin >> a >> b;G[a][b] = G[b][a] = 1;}for(int i = 0; i < k; i++) {cin >> lost_city;memset(vis, 0, sizeof(vis)); //數組初始化int num = -1; //一定有一塊連通塊,因此初值-1 for(int j = 1; j <= n; j++) { //逐個點遍歷 if(vis[j] == 0 && j != lost_city) { //沒遍歷過且不等于x(x城已消失) vis[j] = 1; dfs(j);num++;}cout << num << '\n';} return 0; }

代碼二:拓撲排序解法(待更)


耗時:

總結

以上是生活随笔為你收集整理的【解析】1013 Battle Over Cities (25 分)_31行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。