从m到1的顺序处理数组

用并查集维护链表

http://www.lydsy.com/JudgeOnline/problem.php?id=2054

/**************************************************************
    Problem: 2054
    User: 1349367067
    Language: C++
    Result: Accepted
    Time:3476 ms
    Memory:40244 kb
****************************************************************/
 
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,q,p;
int fa[1000011]={},a[1000011]={};
int findf(int x)
{
    if (fa[x]==0||fa[x]==x) return fa[x]=x;
    else return fa[x]=findf(fa[x]);
}
void init()
{
     scanf("%d%d%d%d",&n,&m,&p,&q);
     int l,r;
     for (int i=m;i>=1;i--)
     {
         l=(((long long)i*p)+q)%n+1;
         r=(((long long)i*q)+p)%n+1;
         if (l>r) swap(l,r);
         for (int j=findf(l);j<=r;j=findf(j))
             a[j]=i,fa[j]=j+1;
     }
     for (int i=1;i<=n;i++)
         printf("%d\n",a[i]);
}
int main()
{
    init();
    return 0;
}
View Code