看到这个题目,第一想法就是重新排列组合source、destination,然后一一比较sourse和destination,再统计循环次数,然后乘以10就行了。
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
typedef struct{
int from;
int to;
int flag;
}Move;
bool cmp(const Move &a,const Move &b){
return a.from < b.from;
}
int main(){
int t,n;
Move *move;
cin>>t;
for(int i = 0; i < t; i ++){
cin>>n;
move = (Move*)malloc(sizeof(Move)*n);
for(int j = 0; j < n; j++){
cin>>move[j].from>>move[j].to;
if(move[j].from > move[j].to){
swap(move[j].from,move[j].to);
}
if(move[j].from % 2 == 0){
move[j].from--;
}
if(move[j].to % 2 == 1){
move[j].to++;
}
move[j].flag = false;
}
sort(move,move+n,cmp);
bool flags_finished = false;
int position_to;
int count = -1;
while(!flags_finished){
flags_finished = true;
count++;
position_to = 0;
for(int j = 0; j < n; j++){
if(position_to < move[j].from && !move[j].flag){
move[j].flag = true;
position_to = move[j].to;
flags_finished = false;
}
}
}
cout<<count*10<<endl;
}
return 0;
}
之后发现这个题目其实不用这么复杂,有个更直接的方法就是直接统计走廊号经过的次数,然后取最高的次数乘以10,就是最少时间。
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX 200+10
int main(){
int t,n;
int record[MAX];
int from,to;
cin>>t;
for(int i = 0; i < t; i++){
memset(record,0,sizeof(record));
cin>>n;
for(int j = 0; j < n; j++){
cin>>from>>to;
if(from > to)
swap(from,to);
if(from % 2 != 0){
from = from / 2 + 1;
}else{
from = from / 2;
}
if(to % 2 != 0){
to = to / 2 + 1;
}else{
to = to / 2;
}
for(int k = from; k <= to; k++){
record[k]++;
}
}
int max = 0;
for(int k = 1; k <= 200; k++){
if(record[k] > max){
max = record[k];
}
}
cout<<10*max<<endl;
}
return 0;
}
如果只针对hdu1005的话,第二种方法更直接更简便。但是如果要输出解决方案,那么第一种应该是一个合理的方法。