题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1050
这道题目隔了很久才做出来的。一开始把判断走廊有重叠的算法都想错了。以为重叠只要满足,下一次moving的起始room小于或等于上一次moving的结束room则证明有重复。这样只能保证局部不能同时进行moving,但是根本得不出其他moving哪些是可以同时进行搬动的。
正确的思路是,统计最大的重叠数,再乘以10即可。具体做法:把每个房间之间的走廊作为一个统计单位,当所有的办公桌都搬运完成之后,看看这段走廊到底需要占用多少次,然后统计所有的走廊被占用的最大值max,这个值就是要单独安排的搬运次数,乘以10就是总的搬运时间。
该算法属于贪心算法,因为它尽可能使搬运办公桌同时进行,以便使单独安排的搬运次数最少。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 int main() 6 { 7 int i, n, cas, from, to, max, table[205]; 8 while (scanf("%d", &cas) != EOF) 9 { 10 while (cas--) 11 { 12 memset(table, 0, sizeof(table)); 13 scanf("%d", &n); 14 while (n--) 15 { 16 scanf("%d%d", &from, &to); 17 if (to < from) // 保证from < to 18 swap(from, to); 19 from = (from - 1) / 2; // 将房间号折算成走廊号 20 to = (to - 1) / 2; 21 for (i = from; i <= to; i++) // 占用走廊情况 22 { 23 table[i]++; // 保存占用走廊的情况 24 } 25 } 26 max = 0; 27 /* for (i = 0; i <= 200; i++) 28 { 29 printf("table[%d] = %d\n", i, table[i]);\ 30 } */ 31 for (i = 0; i <= 200; i++) 32 { 33 if (max < table[i]) 34 max = table[i]; 35 } 36 printf("%d\n", max * 10); // 总的搬运时间 37 } 38 } 39 return 0; 40 }