PAT 1013 Battle Over Cities
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 3
Sample Output:#
1
0
0
思路#
1 #include <iostream> 2 #include <stdio.h> 3 4 5 using namespace std; 6 7 struct Edge 8 { 9 int a; 10 int b; 11 }edge[1100000]; 12 13 int Tree[1100]; 14 15 int findRoot(int x) 16 { 17 if(Tree[x] == -1) 18 return x; 19 int tmp = findRoot(Tree[x]); 20 Tree[x] = tmp; 21 return tmp; 22 } 23 24 25 int main() 26 { 27 int n, m, k; 28 scanf("%d%d%d", &n, &m, &k); 29 30 for(int i = 0; i < m; ++i) 31 scanf("%d%d", &edge[i].a, &edge[i].b); 32 33 int t; 34 for(int x = 1; x <= k; ++x) 35 { 36 scanf("%d", &t); 37 38 // 初始化并查集 39 for(int i = 1; i <= n; ++i) 40 Tree[i] = -1; 41 42 // 遍历所有边,建立并查集 43 for(int i = 0; i < m; ++i) 44 { 45 if(edge[i].a == t || edge[i].b == t) 46 continue; 47 48 int ra = findRoot(edge[i].a); 49 int rb = findRoot(edge[i].b); 50 // 合并 51 if(ra != rb) 52 Tree[ra] = rb; 53 } 54 55 int cnt = 0; //并查集中集合的个数 56 for(int i = 1; i <=n ;++i) 57 { 58 if(Tree[i] == -1) 59 cnt++; 60 } 61 62 if(x == k) 63 cout << cnt-2; 64 else 65 cout << cnt-2 << endl; 66 } 67 68 69 return 0; 70 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南