列车调度c++

代码1

//参考代码1
// #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int a[n] = {0};
    int x;//每次输入的列车序号
    int t = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> x;
        if (t == 0 || a[t - 1] < x) //t-1是因为a[t]是0,a[t-1]才是真正的序号
        //如果最后一个道路的最后一个元素都比x小,
        //说明前几条道路也没有能容下x的了
        {
            a[t] = x; //第一个进去的,一定是这一列最大的
            // printf("t=%d  a[%d]=%d  x=%d\n",t,i,a[i],x);
            t++;
        }
        int l = 0, r = t, mid; //t代表了当前开辟的道路的数量
        while (l < r)
        {
            mid = (r - l) / 2 + l;
            if (x <= a[mid])
            {
                r = mid;
            }
            else
                l = mid+1 ;
        }
        a[l] = x;
        //测试用:
        // for (int j = 0; j < t; j++)
        // {
        //     cout << a[j] << ' ';
        // }
        // cout << endl;
    }
    cout << t;
    return 0;
}

代码2

//参考代码2
#include<iostream> 
using namespace std;
int main(){
	int n;cin>>n;
	int a[n];//a[i]存放的是这条道上的火车中最小的编号。 
	int max = 0;
	int k;
	while(n--){
		cin>>k;
		if(max == 0 || a[max-1] < k){//当道为零或者或者所有道的最小号都小于新来的号码,需要加一条道来放这个号码 
			a[max++] = k;
		}
		else{//有道能放下新来的,找到比新来的大且和间距最小的那个道,用新来的覆盖它的号码 ,二分查找 
			int l=0;int r=max-1;
			while(l<r)
			{
				int mid=l+(r-l)/2;
				if(a[mid]>k)
				{
					r=mid-1;
				}
				else
				{
					l=mid+1;
				}
			}
			a[l]=k;
		}
	}
	cout<<max;
	return 0;
}

代码3

//参考代码3
#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int a[N],cnt,n;
int find(int x)
{
	if(cnt==0)return 0;
	int l=0,r=cnt-1;
    while(l<r)
    {
    	int mid=l+r>>1;
    	if(a[mid]>x)r=mid;
    	else l=mid+1;
    }
    if(a[r]>x)return r;
	return cnt;
}
int main()
{
	cin>>n;
	for(int i=0;i<n;++i)
	{
		int x;cin>>x;
		int t=find(x);
		if(t==cnt)a[cnt++]=x;
		else a[t]=x;
	}
	cout<<cnt;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值