Spoors
Time Limit: 1 Sec Memory Limit: 128 MB
Description
Some of you may know when a snail crawls; he will leave a spoor after his tour. Then all of you will know that when many snail crawls, they will leave many spoors. In this problem, you will be given n snails’
spoors, then calculate the sum of length of their spoors. To make it harder, we assume that all the snail crawl on the same line. That is to say, when two snails’ spoor overlaps, the length of the overlap part is considered only once.
Input
There are many test cases.
In each case, the first line is a single integer n (0<n<=1000), indicating n snails.
Following n lines, in each line there are two integer a and b (0<a, b<=1000), indicating a snail crawls from point (0,a) to point (0,b). I warn that the length of (0,a) to (0,b) is |b-a+1|.
Proceed to End Of File.
Output
For each case, output one line with a single integer, indicating the sum length of the spoors.
Sample Input
12 426 32 551 95 73 19 25 5
Sample Output
359
题意:有一只蜗牛,在一条路上爬了好多次,每次都有个起点a和终点b,每次爬过都会在路上留下印记,问这条路上总共有多长是有印记的(重复的只算一次)。
分析:预处理一下,每次都有个起点和终点, 每次都把起点和终点间的路标记一下,到最后,看有多长是被标记过的即可。
AC代码:
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; int a[1005]; int main(){ // freopen("in.txt", "r", stdin); int n, x, y; while(scanf("%d", &n)!=EOF){ memset(a, 0, sizeof(a)); int fo = 0; for(int i=0; i<n; i++){ scanf("%d%d", &x, &y); if(x > y) swap(x, y); //x有可能比y大 if(y > fo) fo = y; for(int i=x; i<=y; i++) a[i] = 1; //标记 } int ans = 0; for(int i=0; i<=fo; i++){ //检查有多少是被标记的 if(a[i]) ans ++; } printf("%d\n", ans); } }
这种方法还是很常用的,我以前最开始是从tourist的代码里看到的,很神奇的方法^_^