HDU 3461 Code Lock (并查集)
Code Lock
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 821 Accepted Submission(s): 292
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 1
1 1
2 1
1 2
Sample Output
1
26
Author
hanshuai
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ int n,m,Max=10000010,count=0; BigInteger mod=BigInteger.valueOf(1000000007); int patten[]=new int[Max]; public static void main(String args[]){ new Main().work(); } void work(){ Scanner sc=new Scanner(new BufferedInputStream(System.in)); while(sc.hasNext()){ n=sc.nextInt(); m=sc.nextInt(); init(); for(int i=0;i<m;i++){ int a=sc.nextInt(); a--;//给定数据[a,b]我们要求(a,b]这样无须考虑端点问题 int b=sc.nextInt(); union(a,b); } System.out.println(pow(26,(n-count)).mod(mod)); } } //快速幂取余 BigInteger pow(int a,int b){ BigInteger sum=BigInteger.ONE; BigInteger big=BigInteger.valueOf(a); while(b!=0){ if((b&1)!=0) sum=(sum.multiply(big)).mod(mod); big=(big.multiply(big)).mod(mod); b>>=1; } return sum; } //并查集合并 void union(int a,int b){ int pa=fun(a); int pb=fun(b); if(pa==pb) return; if(pa>pb){ count++; patten[pb]=pa; } else{ count++;//不同的字符串,即可以操作的区间,然后用n-count; patten[pa]=pb; } } //并查集查找 int fun(int x){ if(patten[x]==x) return x; patten[x]=fun(patten[x]);//路径压缩 return patten[x]; } //初始化 void init(){ count=0; for(int i=0;i<=n;i++){ patten[i]=i; } } }
补充:软件开发 , C++ ,