程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU 3461 Code Lock (並查集)

HDU 3461 Code Lock (並查集)

編輯:C++入門知識

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;
		}
	}
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved