链接: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;
}
1350

被折叠的 条评论
为什么被折叠?



