【解析】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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【解析】1012 The Best Ra
- 下一篇: 【题目解析】1015 Reversibl