#C++初学记录(算法4)

A - Serval and Bus
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.

Serval will go to the bus station at time t, and there are n bus routes which stop at this station. For the i-th bus route, the first bus arrives at time si minutes, and each bus of this route comes di minutes later than the previous one.

As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.

Input
The first line contains two space-separated integers n and t (1≤n≤100, 1≤t≤105) — the number of bus routes and the time Serval goes to the station.

Each of the next n lines contains two space-separated integers si and di (1≤si,di≤105) — the time when the first bus of this route arrives and the interval between two buses of this route.

Output
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.

Examples
Input
2 2
6 4
9 5
Output
1
Input
5 5
3 3
2 5
5 6
4 9
6 1
Output
3
Input
3 7
2 2
2 3
2 4
Output
1
正确代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    long long s[105],d[105], maxx = INT_MAX, flag = 0, n, t,temp,temp1;
    scanf("%lld%lld", &n, &t);
    for(int i = 1; i <= n; i++){
        scanf("%lld%lld", &s[i], &d[i]);
        if(s[i] >= t && maxx>s[i]){
            maxx = s[i];
            if(maxx == t){
                flag = 1;
                temp1 = i;
            }
            temp = i;
        }
    }
    //cout << maxx <<" " <<temp << endl;
    if(maxx != INT_MAX &&flag == 1){
        printf("%lld\n", temp1);
        return 0;
    }
    for(int i = 1; i <= n; i++){
        while(maxx > s[i] && s[i] < t){
            s[i] += d[i];
        }
    }
//    for(int i = 1; i <= n; i++){
//        printf("%lld ", s[i]);
//    }
//    printf("\n");
    for(int i = 1; i <= n; i++){
        if(maxx > s[i]){
            maxx = s[i];
            temp = i;
        }
    }
    printf("%lld\n", temp);
}

代码理解
nt的意义分别是公交车的数量和主人公到达的时间,每一路段的公交车都和现实生活中一样由多辆公交车有时段间隔的进行行驶,之后n个循环输入的s和d是每段首辆公交车到主人公站点的时间和下一辆车到达时间的间隔,maxx里面存储的是最短时间,即公交车不管是首班还是中途哪班只要间隔和主人公到达时间最短则会保存在maxx变量里面。因为要输入n个数据进入s和d数组,所以maxx里的数据会不停的改变。这里有几个极限判断,即是车到达时间和主人公到达时间相同时,则会跳出循环直接输出车次。temp1是记录时间间隔最短的车次、到最后一个数据输入完毕,计算机的运行也到此结束,因此输出step1,结束程序。

猜你喜欢

转载自www.cnblogs.com/xiaofengqaq/p/10725501.html