HDU 1050 Moving Tables(貪心 差分)
Problem Description
The famous ACM (Advanced Computer Maker) Company has rented a floor of a building whose shape is in the following figure.
The floor has 200 rooms each on the north side and south side along the corridor. Recently the Company made a plan to reform its system. The reform includes moving a lot of tables between rooms. Because the corridor is narrow and all the tables are big, only one table can pass through the corridor. Some plan is needed to make the moving efficient. The manager figured out the following plan: Moving a table from a room to another room can be done within 10 minutes. When moving a table from room i to room j, the part of the corridor between the front of room i and the front of room j is used. So, during each 10 minutes, several moving between two rooms not sharing the same part of the corridor will be done simultaneously. To make it clear the manager illustrated the possible cases and impossible cases of simultaneous moving.
Input
The input consists of T test cases. The number of test cases ) (T is given in the first line of the input. Each test case begins with a line containing an integer N , 1<=N<=200 , that represents the number of tables to move. Each of the following N lines contains two positive integers s and t, representing that a table is to move from room number s to room number t (each room number appears at most once in the N lines). From the N+3-rd line, the remaining test cases are listed in the same manner as above.
Output
The output should contain the minimum time in minutes to complete the moving, one per line.
Sample Input
3
4
10 20
30 40
50 60
70 80
2
1 3
2 200
3
10 100
20 80
30 50
Sample Output
10
20
30
思路
使用貪心演算法。記錄每一個通道使用的次數,使用次數最多的通道乘每次的時間即為最短時間。
下面證明一下:
假設通道使用次數最多的為N。先搬經過需要被經過N此通道的桌子(幾個不相交的區間同時搬,可能存在也為N的此時搬不了,後面證明這種情況不可能),如果這次搬之後,所有通道的次數最大為N-1,那麼再搬第二次,最大就為N-2,搬N次,最大就為0,也就是所有都為0,所有桌子都搬完了。
另外,注意
輸入前面的數不一定大於後面的數
3-5和6-8有重疊 (5和6的通道相同)
程式碼
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int pas[205];
int main()
{
int t;
cin>>t;
while(t--)
{
memset(pas,0,sizeof(pas));
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(a>b)
swap(a,b);
a=(a+1)/2;
b=(b+1)/2; //計算通道
for(int i=a;i<=b;i++)
pas[i]++;
}
int maxx=0;
for(int i=1;i<=201;i++)
maxx=max(maxx,pas[i]);
cout<<maxx*10<<endl;
}
return 0;
}
還可以用差分,時間複雜度更小
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int pas[205];
int main()
{
int t;
cin>>t;
while(t--)
{
memset(pas,0,sizeof(pas));
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(a>b)
swap(a,b);
a=(a+1)/2;
b=(b+1)/2;
pas[a]++;
pas[b+1]--;
}
for(int i=1;i<=201;i++)
pas[i]+=pas[i-1];
int maxx=0;
for(int i=1;i<=201;i++)
maxx=max(maxx,pas[i]);
cout<<maxx*10<<endl;
}
return 0;
}