【PAT甲级 - 1013】Battle Over Cities (25分)(并查集)
題干:
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.
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??.
Input 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.
Output Specification:
For each of the?K?cities, output in a line the number of highways need to be repaired if that city is lost.
Sample Input:
3 2 3 1 2 1 3 1 2 3Sample Output:
1 0 0題目大意:
給定n個點m條邊的無向圖,有k次詢問,每次詢問一個點,問去掉和這個點相連的所有的邊以后,還需要添加幾條邊可以使得圖為一個連通圖。(n<1000)
解題報告:
這題掉坑了啊,,想當然以為m也<1000,因為這樣才符合復雜度,但是這題其實沒說m和k的復雜度,所以m最大可以到一個完全圖n*(n-1)/2,也就是5e5左右,所以需要把邊數開大一點才可以過。但是這樣復雜度就不對了呀,,看了一下數據,大數據下k<20,也就是說查詢很少,,所以預處理的話就非常不劃算,因為PAT題經常容易數據水(??),所以直接暴力就行別預處理了。。。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e6 + 5; int n,m,k,u[MAX],v[MAX],f[MAX]; int getf(int v) {return f[v] == v ? v : f[v] = getf(f[v]); } void merge(int u,int v) {int t1 = getf(u),t2 = getf(v);f[t2] = t1; } int main() {cin>>n>>m>>k;for(int i = 1; i<=m; i++) {scanf("%d%d",u+i,v+i);}while(k--) {int tar,cnt = 0;scanf("%d",&tar);for(int i = 1; i<=n; i++) f[i] = i;for(int i = 1; i<=m; i++) {if(u[i] == tar || v[i] == tar) continue;merge(u[i],v[i]); }for(int i = 1; i<=n; i++) {if(f[i] == i) cnt++;}printf("%d\n",max(cnt-2,0));}return 0 ; }?
總結
以上是生活随笔為你收集整理的【PAT甲级 - 1013】Battle Over Cities (25分)(并查集)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拜登当选对美元有什么影响?美元会大幅贬值
- 下一篇: 储户们注意,本月起银行存款要“变脸”了,