EOJ 2069 Asteroids
1
/*
2
EOJ 2069 Asteroids
3
4
5
----問題描述:
6
7
Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500).
8
The grid contains K asteroids (1 <= K <= 10,000), which are conveniently located at the lattice points of the grid.
9
10
Fortunately, Bessie has a powerful weapon that can vaporize all the asteroids in any given row or column of the grid with a single shot.
11
This weapon is quite expensive, so she wishes to use it sparingly.
12
Given the location of all the asteroids in the field, find the minimum number of shots Bessie needs to fire to eliminate all of the asteroids.
13
14
15
----輸入:
16
17
* Line 1: Two integers N and K, separated by a single space.
18
* Lines 2..K+1: Each line contains two space-separated integers R and C (1 <= R, C <= N) denoting the row and column coordinates of an asteroid, respectively.
19
20
21
----輸出:
22
* Line 1: The integer representing the minimum number of times Bessie must shoot.
23
24
25
----樣例輸入:
26
27
3 4
28
1 1
29
1 3
30
2 2
31
3 2
32
33
34
----樣例輸出:
35
36
2
37
38
39
----分析:
40
41
建立二分圖模型,
42
若第 i 行和第 j 列處存在一個 asteroid ,則 x[i] 與 y[j] 連一條邊,
43
求二分圖最大匹配,使用匈牙利算法。
44
45
*/
46
47
48
#include <stdio.h>
49
#include <string.h>
50
51
#define L 503
52
53
int adj[ L ][ L ], n, state[ L ], result[ L ];
54
55
int find( int i ) {
56
int j, k;
57
for ( j = adj[ i ][ 0 ]; j > 0; --j ) {
58
k = adj[ i ][ j ];
59
if ( state[ k ] == 0 ) {
60
state[ k ] = 1;
61
if ( ( result[ k ] == 0 ) || find( result[ k ] ) ) {
62
result[ k ] = i;
63
return 1;
64
}
65
}
66
}
67
return 0;
68
}
69
70
int maxMatch() {
71
int ans = 0, i;
72
for ( i = 1; i <= n; ++i ) {
73
memset( state, 0, sizeof( state ) );
74
if ( find( i ) )
75
++ans;
76
}
77
return ans;
78
}
79
80
int main() {
81
int i, j, k;
82
memset( adj, 0, sizeof( adj ) );
83
memset( result, 0, sizeof( result ) );
84
scanf( "%d%d", &n, &k );
85
while ( k-- ) {
86
scanf( "%d%d", &i, &j );
87
adj[ i ][ ++adj[ i ][ 0 ] ] = j;
88
}
89
printf( "%d\n", maxMatch() );
90
return 0;
91
}
92

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

posted on 2012-03-30 22:18 coreBugZJ 閱讀(524) 評論(0) 編輯 收藏 引用 所屬分類: ACM 、Algorithm 、課內作業