简单的并查集应用。
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; const int maxn = 100000 + 10; int ll[maxn], rr[maxn]; int f1(int x) { if (x != ll[x]) ll[x] = f1(ll[x]); return ll[x]; } int f2(int x) { if (x != rr[x]) rr[x] = f2(rr[x]); return rr[x]; } int main() { int n, m, i, a, b, j; while (~scanf("%d%d", &n, &m)) { if (n == 0 && m == 0) break; for (i = 0; i <= n; i++) ll[i] = i, rr[i] = i; for (i = 0; i < m; i++) { scanf("%d%d", &a, &b);
for (j = a; j <= b; j++) ll[j] = a; ll[a] = a - 1; for (j = a; j <= b; j++) rr[j] = b; rr[b] = b + 1; int zuo = f1(a); int you = f2(b); if (zuo == 0 || zuo == n + 1) printf("* "); else printf("%d ", zuo); if (you == n + 1 || you == 0) printf("* "); else printf("%d ", you); } printf("- "); } return 0; }