入门模拟-简单模拟:1046 Shortest Distance (20 分)
题目
The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.
Input Specification:
Output Specification:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
Sample Input:
5 1 2 4 14 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
题解
1、解法一(最后一个测试点timeover)
最开始做这题的时候感觉是不是dijsktra算法呀,后来看到后面给的是查询操作不是给的两个结点之间的通路问题。这就像是一道模拟题啦,给定两个结点,分别求出两个结点之间的距离以及回路补集的距离,输出最小的一个即可。
(1)注意两个结点的大小关系,采用交换;
(2)先存储到vector当中,读入始末两个结点后,遍历容器求出其中一边的距离,这也是给timeover埋下了一个坑!
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
int temp;
vector<int> vec;
int num = 0;
for(int i = 0 ; i < n ; i++){
cin >> temp;
vec.push_back(temp);
num += temp;
}
int number;
int first,end;
int fir_cnt = 0,end_cnt = 0;
cin >> number;
while(number--){
int num_temp = 0;
cin >> first >> end;
if(first > end)
swap(first , end);
for(int j = first - 1 ; j < end - 1 ; j++){
num_temp += vec[j];
}
if(num_temp > num - num_temp)
cout << num - num_temp << endl;
else
cout << num_temp << endl;
}
return 0;
}
2、解法二
(1)两个结点出现first > end时,最好使用algorithm中的min()函数,一步输出;
//冗余代码
if(num_temp > num - num_temp)
cout << num - num_temp << endl;
else
cout << num_temp << endl;
//优化
int num_temp = dis[end] - dis[first];
cout << min(num - num_temp,num_temp) << endl;
(2)此题如果没有经过预处理dis 数组和sum 的做法会很容易超时。这是因为在极端情况下,每次查询都需要遍历整个数组, 即有10 ^5次操作,而共有10 ^4 个查询, 所以极端情况会有10 ^9 次操作,这在200ms 的时限内是不能承受的。
O(n)->O(1) ! ! ! ! !
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 100005;
int dis[MAXN];
int main()
{
int n;
cin >> n;
int temp;
int num = 0;
for(int i = 1 ; i <= n ; i++){
cin >> temp;
dis[i] = num;//此处存储1号结点到i号结点的距离
num += temp;//累加
}
int number;
int first,end;
int fir_cnt = 0,end_cnt = 0;
cin >> number;
while(number--){
cin >> first >> end;
if(first > end)
swap(first , end);
int num_temp = dis[end] - dis[first];
cout << min(num - num_temp,num_temp) << endl;//优化
}
return 0;
}
小结
一定要养成一边读取数据,一边处理数据的习惯,可能会对核心代码的求解有创造性的时空降低。