题目:点击打开题目链接
思路:为了满足所有的车不能相互攻击,就要保证所有的车不同行不同列,于是可以发现,行与列是无关的,因此题目可以拆解为两个一维问题,即在区间[1-n]之间选择n个不同的整数,使得第i个整数在区间[x, y]内,此问题可以通过贪心法解决,但需要注意选择合适的贪心策略。我的贪心方法是:以后约束点为重点考察对象对点进行排序,然后遍历给每一个点选择最小的合适的下标,若找不到合适的下标,说明无解。
AC代码:
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 5 using namespace std; 6 7 const int maxn = 5000 + 5; 8 9 struct point{ 10 int st, ed, id; 11 }x[maxn], y[maxn]; 12 13 int n, cx[maxn], cy[maxn]; 14 15 bool cmp(const point& temp1, const point& temp2) { 16 return temp1.ed == temp2.ed ? temp1.st < temp2.st : temp1.ed < temp2.ed; 17 } 18 19 bool judge(int *arr, point *Point) { 20 sort(Point, Point + n, cmp); 21 int temp[maxn] = {0}; 22 23 for(int i = 0; i < n; i++) { 24 bool ok = false; 25 for(int j = Point[i].st; j <= Point[i].ed; j++) { 26 if(!temp[j]) { 27 ok = true; 28 temp[j] = 1; 29 arr[Point[i].id] = j; 30 break; 31 } 32 } 33 if(!ok) return false; 34 } 35 return true; 36 } 37 38 int main() 39 { 40 while(cin >> n && n) { 41 for(int i = 0; i < n; i++){ 42 cin >> x[i].st >> y[i].st >> x[i].ed >> y[i].ed; 43 x[i].id = i; 44 y[i].id = i; 45 } 46 memset(cx, 0, sizeof(cx)); 47 memset(cy, 0, sizeof(cy)); 48 if(judge(cx, x) && judge(cy, y)) { 49 for(int i = 0; i < n; i++) 50 cout << cx[i] << ' ' << cy[i] << endl; 51 } 52 else 53 cout << "IMPOSSIBLE" << endl; 54 55 } 56 return 0; 57 }