Code Lock(並查集 + 快速冪)

Code Lock
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 277 Accepted Submission(s): 127

Problem Description
A lock you use has a code system to be opened instead of a key. The lock contains a sequence of wheels. Each wheel has the 26 letters of the English alphabet ‘a’ through ‘z’, in order. If you move a wheel up, the letter it shows changes to the next letter in the English alphabet (if it was showing the last letter ‘z’, then it changes to ‘a’).
At each operation, you are only allowed to move some specific subsequence of contiguous wheels up. This has the same effect of moving each of the wheels up within the subsequence.
If a lock can change to another after a sequence of operations, we regard them as same lock. Find out how many different locks exist?

There are several test cases in the input.

Each test case begin with two integers N (1<=N<=10000000) and M (0<=M<=1000) indicating the length of the code system and the number of legal operations.
Then M lines follows. Each line contains two integer L and R (1<=L<=R<=N), means an interval [L, R], each time you can choose one interval, move all of the wheels in this interval up.

The input terminates by end of file marker.

For each test case, output the answer mod 1000000007

Sample Input
1 1
1 1
2 1
1 2

Sample Output

有n個字母 執行m個操作 然后問如果考慮這n個字母則有26的n次方種 然而題目要求中又說了 當執行之種可執行的操作 則認為是統一序列 所以只需要用N - 可執行的序列種數 的26 次方即可
而這里需要注意的是[1,3][3,5][1,5]這是三把不同的鎖 因為3執行了兩次
而[1,3][4,5][1,5] 則是兩把鎖
所以我們在合並時只需要合並[l-1,r] 這個區間即可


using namespace std;

long long mod = 1000000007;
long ff[10000007];
long num =0;
long father(int x)
int i = x;
x = ff[x];

/* while(i!=x)//壓縮路徑
int j = ff[i];
ff[i] = x;
i = j;

return x;
void Union_set(int l,int r)
long pa = father(l);
long pb = father(r);
ff[pa] = pb;
long long exp(long n)//快速冪算法
long long sum =1;
long long tmp =26;
sum = sum * tmp;
sum %= mod;
tmp = (tmp *tmp) % mod;
n = n /2;//向右移動一位
return sum;
int main()
int n,m;
num =0;
for(int i =0;i<=n;i++)//初始化 這列由於我判斷是l-1 所以最左邊是0
ff[i] = i;
for(int i =0;i<m;i++)
int l,r;
Union_set(l-1,r);//這里只需要判斷Union_set(l-1,r) 或者 Union_set(l,r+1) 即可
return 0;

1 1
1 1
2 1
1 2



粤ICP备14056181号  © 2014-2021