城市规划【贪心】

链接:https://www.nowcoder.com/acm/contest/180/C
 

题目描述

小a的国家里有n个城市,其中第i和第i - 1个城市之间有无向道路连接,特殊的,第1个城市仅与第2个城市相连

为了减轻道路维护负担,城市规划局局长MXT给出了m个要求,他想让小a断开一些道路,使得任意1 ≤ i ≤ m ,城市xi不能到达城市yi

同时最小化断开道路的数量。

 

输入描述:

第一行两个整数n, m,分别表示城市的数量和请求的数量
接下来m行,每行两个整数x,y,表示需要使得x不能到达y

输出描述:

输出一个整数,表示最小断开桥的数量

示例1

输入

复制

4 2
1 3
2 4

输出

复制

1

说明

可以断开(2, 3)城市之间的道路

示例2

输入

复制

4 3
1 3
2 4
1 2

输出

复制

2

说明

可以断开(1, 2) (2, 3)之间的道路

备注:

对于100%的数据:n ≤ 106, m ≤ 107
本题不卡常数,请设计严格线性做法

读入文件较大,请使用读入优化,本机调试时请使用文件输入输出
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
用法:
int a = read(), b = read();
std::cout << a + b;

由于nowcoder的编译器限制,如果需要在程序中开107级别的数组,可能会出现内存超限的情况,请使用new函数手动申请
用法:

int* P = new int[(int)1e7 + 10];

分析:

贪心排序的话会超时,从前往后扫描不会超时,因为只有1e6个点,如果起点相同可以用数组存放

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e6+5;
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
inline int read()
{   
    char c = getchar();
    int x = 0, f = 1;
    while(c < '0' || c > '9') {
        if(c == '-') f = -1; c = getchar();
    }
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int vis[maxn];
int main()
{
    int n = read(), m = read();
    for(int i = 1; i <= n; ++i) {
        vis[i] = n+1;
    }
    for(int i = 0; i < m; ++i) {
        int x, y;
        x = read(), y = read();
        if(x > y)   swap(x, y);
        vis[x] = min(vis[x], y);
    }
    int ans = 0, res = n+1;
    for(int i = 1; i <= n; ++i) {
        res = min(res, vis[i]);
        if(i == res) {
            ++ans;
            res = vis[i];
        }
    }
    printf("%d\n", ans);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值