hdu3461之并查集

来源:互联网 发布:友情链接源码 编辑:程序博客网 时间:2024/06/04 18:55

Code Lock

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 722    Accepted Submission(s): 245


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?
 


 

Input
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.
 


 

Output
For each test case, output the answer mod 1000000007
 


 

Sample Input
1 11 12 11 2
 


 

Sample Output
126

题目的意思是有一个字母锁,含有n个字母,然后给定m个区间,并规定区间里面的那一段字母是可以同时改变的,比如a变为b,b变为c,z变为a之类的,然后如果锁可以通过有限次变换变成相同的,就规定为同一把锁。然后要求有多少把不同的锁。

 

思路是看别人的,目前还不是很理解为什么每增加一个区间则n-1

思路(转):解题思路:
        首先确认下如果没有这种区间存在,那么锁的种类总共有26^n个,而出现了一个区间n就得减去1,因为无论是在哪个区间,也不管区间的长度多长,出现了一个区间,就代表这个区间有26种相同的排列组合要排除掉。所以是原来的26^n/26=26^(n-1).举个例子,比如n=5,有a,b,c,e,d.区间为2~4,原来的组合数是26^n,现在b,c,e,有26种是相同的,所以要除26.只是要注意一种特殊的情况,就是比如有一个区间1~5,还有一个区间1~2,那么就等于隐含了一个存在的区间3~5,因为区间3~5可以由前两个区间生成。

 

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<map>#include<iomanip>#define INF 99999999using namespace std;const int MAX=10000000+10;const int mod=1000000007;int father[MAX],n,m;void makeset(int num){for(int i=0;i<=num;++i){father[i]=i;}}int findset(int v){if(v != father[v])father[v]=findset(father[v]);return father[v];}void Union(int x,int y){int a=findset(x);int b=findset(y);if(a == b)return;father[b]=a;--n;}__int64 fastpow(__int64 a,int b){__int64 sum=1;while(b){if(b&1)sum=(sum*a)%mod;a=(a*a)%mod;b>>=1;}return sum;}int main(){int a,b;while(scanf("%d%d",&n,&m)!=EOF){makeset(n+1);for(int i=0;i<m;++i){scanf("%d%d",&a,&b);Union(a,b+1);}printf("%I64d\n",fastpow((__int64)26,n));}return 0;} 


 

原创粉丝点击