题解 | #Tallest Cow#

Tallest Cow

https://ac.nowcoder.com/acm/problem/25044

题目描述

FJ's N (1 ≤ N ≤ 10,000) cows conveniently indexed 1..N are standing in a line. Each cow has a positive integer height (which is a bit of secret). You are told only the height H (1 ≤ H ≤ 1,000,000) of the tallest cow along with the index I of that cow.
FJ has made a list of R (0 ≤ R ≤ 10,000) lines of the form "cow 17 sees cow 34". This means that cow 34 is at least as tall as cow 17, and that every cow between 17 and 34 has a height that is strictly smaller than that of cow 17.
For each cow from 1..N, determine its maximum possible height, such that all of the information given is still correct. It is guaranteed that it is possible to satisfy all the constraints.

输入描述:

Line 1: Four space-separated integers: N, I, H and R
Lines 2..R+1: Two distinct space-separated integers A and B (1 ≤ A, B ≤ N), indicating that cow A can see cow B.

输出描述:

Lines 1..N: Line i contains the maximum possible height of cow i.
示例1

输入

9 3 5 5
1 3
5 3
4 3
3 7
9 8

输出

5
4
5
3
4
4
5
5
5
注:这一题数据会有重复,可以开表或者是二维数组来去重,不去重的话答案只能通过50%.
这一题上面的大佬都是用了差分数组的前缀和来写的,代码如下(没用map)
#include<stdio.h>
#include<bits/stdc++.h>
struct ss{
    int L,R;
}s[10020];
int d[10020],sum[10020];
int st[10020][10020];
using namespace std;
int main(){
    int i,j,N,I,H,R;
    scanf("%d%d%d%d",&N,&I,&H,&R);
    for(i=0;i<R;i++){
        scanf("%d%d",&s[i].L,&s[i].R);
        if(s[i].L>s[i].R){
            swap(s[i].L,s[i].R);
        }
        if(st[s[i].L][s[i].R]) continue;
        else st[s[i].L][s[i].R]=1;
        sum[s[i].L+1]--;
        sum[s[i].R]++;
    }
    int ans=H;
    for(i=1;i<=N;i++){
        ans+=sum[i];
        printf("%d\n",ans);
    }
    return 0;
}

因为这一题虽然是O(n^2),但是数据相对较小,所以可以不用差分与前缀和直接求解,思路相同,代码如下
#include<stdio.h>
#include<bits/stdc++.h>
struct ss{
    int L,R;
}s[10020];
int d[10020];
int st[10020][10020];
using namespace std;
int main(){
    int i,j,N,I,H,R;
    scanf("%d%d%d%d",&N,&I,&H,&R);
    for(i=0;i<R;i++){
        scanf("%d%d",&s[i].L,&s[i].R);
        if(s[i].L>s[i].R){
            swap(s[i].L,s[i].R);
        }
        if(st[s[i].L][s[i].R]) continue;
        else st[s[i].L][s[i].R]=1;
        for(j=s[i].L+1;j<s[i].R;j++){
            d[j]--;
        }
    }
    for(i=1;i<=N;i++){
        printf("%d\n",d[i]+H);
    }
    return 0;
}
//

这是本人对于算法入门班共十三章习题的题解与个人的一些感悟,本人写题解的目的是对于某些经典的/陌生的/无从下手的/思维方向错误的题目加深印象。 希望自己能够在学习算法的路上走得更远,今天也是努力学习的一天!

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务