【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個(gè)點(diǎn)m條邊的無向圖,有k次詢問,每次詢問一個(gè)點(diǎn),問去掉和這個(gè)點(diǎn)相連的所有的邊以后,還需要添加幾條邊可以使得圖為一個(gè)連通圖。(n<1000)
解題報(bào)告:
這題掉坑了啊,,想當(dāng)然以為m也<1000,因?yàn)檫@樣才符合復(fù)雜度,但是這題其實(shí)沒說m和k的復(fù)雜度,所以m最大可以到一個(gè)完全圖n*(n-1)/2,也就是5e5左右,所以需要把邊數(shù)開大一點(diǎn)才可以過。但是這樣復(fù)雜度就不對(duì)了呀,,看了一下數(shù)據(jù),大數(shù)據(jù)下k<20,也就是說查詢很少,,所以預(yù)處理的話就非常不劃算,因?yàn)镻AT題經(jīng)常容易數(shù)據(jù)水(??),所以直接暴力就行別預(yù)處理了。。。
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 ; }?
總結(jié)
以上是生活随笔為你收集整理的【PAT甲级 - 1013】Battle Over Cities (25分)(并查集)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拜登当选对美元有什么影响?美元会大幅贬值
- 下一篇: cdn转发防攻击_高防CDN和高防服务器