PTA列车调度
一、题目描述
二、解题思路
刚开始想到的是直接暴力模拟算出答案,然后超时了,后来发现其实对于每个轨道,如果需要新增轨道,那么最后那个列车的编号一定是递增的,那么此时我们可以采用二分优化这个搜索过程。优化后成功AC。
比如样例
你会发现每次插入都是递增的,故可以采用二分优化算法。
三、代码实现
1 #include "bits/stdc++.h" 2 #define PII pair<int,int> 3 #define rep(i,z,n) for(int i = z;i <= n; i++) 4 #define per(i,n,z) for(int i = n;i >= z; i--) 5 #define ll long long 6 #define db double 7 #define vi vector<int> 8 #define debug(x) cerr << "!!!" << x << endl; 9 using namespace std; 10 //从某个串中把某个子串替换成另一个子串 11 string& replace_all(string& src, const string& old_value, const string& new_value) { 12 // 每次重新定位起始位置,防止上轮替换后的字符串形成新的old_value 13 for (string::size_type pos(0); pos != string::npos; pos += new_value.length()) { 14 if ((pos = src.find(old_value, pos)) != string::npos) { 15 src.replace(pos, old_value.length(), new_value); 16 } 17 else break; 18 } 19 return src; 20 } 21 inline ll read() 22 { 23 ll s,r; 24 r = 1; 25 s = 0; 26 char ch = getchar(); 27 while(ch < '0' || ch > '9'){ 28 if(ch == '-') 29 r = -1; 30 ch = getchar(); 31 } 32 while(ch >= '0' && ch <= '9'){ 33 s = (s << 1) + (s << 3) + (ch ^ 48); 34 ch = getchar(); 35 } 36 return s * r; 37 } 38 inline void write(ll x) 39 { 40 if(x < 0) putchar('-'),x = -x; 41 if(x > 9) write(x / 10); 42 putchar(x % 10 + '0'); 43 } 44 int vis[100100]; 45 int a[100010]; 46 int n; 47 int solve() 48 { 49 int res = 1; 50 vis[res] = a[1]; 51 rep(i,2,n){ 52 int pos = INT_MAX; 53 bool ok = false; 54 int l = 1; 55 int r = res; 56 while(l <= r){ 57 int m = (l + r) >> 1; 58 if(vis[m] >= a[i]){ 59 pos = min(pos,m); 60 ok = true; 61 r = m - 1; 62 } 63 else 64 l = m + 1; 65 } 66 if(!ok) 67 vis[++res] = a[i]; 68 else 69 vis[pos] = a[i]; 70 } 71 return res; 72 } 73 int main() 74 { 75 n = read(); 76 rep(i,1,n) 77 a[i] = read(); 78 write(solve()); 79 return 0; 80 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}