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 city1-city2 and city1-city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.
例如,如果我们有3个城市和2条高速公路连接城市1-城市2和城市1-城市3. 如果城市1被敌人占领了,我们必须修复1条公路,那就是公路城2-城市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.
每个输入文件包含一个测试用例。每种情况都从一条包含3个数字N(<1000)、M和K的线开始,这3个数字分别是城市总数、剩余高速公路数量和待检查城市数量。接下来是M条线,每条线用2个整数来描述一条公路,这是公路连接的城市的数量。这些城市的编号从1到N。最后是一条包含K数字的线,这些数字代表了我们关注的城市。
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.
对于K个城市中的每一个,如果该城市丢失,一条线路中需要修复的公路数量。
Sample Input:
3 2 3
1 2
1 3
1 2 3
Sample Output:
1
0
0
思路:图论,用二维数组存储图,然后进行深度优先搜索dfs,看有几个连通分量,最后所需要修的路就等于连通分量数量 - 1.这题必须得用io流输入方式输入,不然最后一个测试点会超时
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;
class Main{
static int [][]graph;
static boolean []visited;
static int n;
public static void main(String[] args)throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(bf);
in.nextToken();
n = (int)in.nval;
graph = new int[n][n];
visited = new boolean[n];
in.nextToken();
int m = (int)in.nval;
in.nextToken();
int k = (int)in.nval;
while(m-- > 0)
{
in.nextToken();
int x = (int)in.nval - 1;
in.nextToken();
int y = (int)in.nval - 1;
graph[x][y] = 1;
graph[y][x] = 1;
}
while(k -- > 0)
{
Arrays.fill(visited,false);
in.nextToken();
int city = (int)in.nval - 1;
visited[city] = true;
int count = 0;
for(int i = 0 ; i < n ;i++)
{
if(!visited[i])
{
dfs(i);
count ++;
}
}
System.out.println(count - 1);
}
}
public static void dfs(int root)
{
visited[root] = true;
for(int i = 0 ; i < n ;i++)
{
if(visited[i] == false && graph[root][i] == 1)
{
dfs(i);
}
}
}
}