求解n元方程

求解形如 k1*x1^p1+k2*x2^p2.........=0 的方程。输出有多少解。

-20=<k_{i}<=20,1=<p_{i}<=4,n表示n元方程,1=<n<=4,未知数1=<x_{i}<=M, 1<=M<=150;

第一行输入一个整数n,

第二行输入一个整数M,

第三行到n+2行,每行2个整数,分别为 k_{i},p_{i}.

输入样例:

3
100
1 2
-1 2
1 2

输出:

104

dfs深搜

代码如下:

import java.util.Scanner;

public class L5 {

	static int n, M, ans = 0;
	static int[] k = new int[5];
	static int[] p = new int[5];

	static long pow(int x, int y) {
		if (y == 0)
			return 1;
		else if (y % 2 == 0) {
			long t = pow(x, y / 2);
			return t * t;
		} else {
			long t = pow(x, y / 2);
			return t * t * x;
		}
	}
     //x:第x位,s:结果
	static void dfs(int x, long s) {
		if (x == n) {
			if (s == 0) {
				ans++;
			}
			return;
		}
		for (int i = 1; i <= M; i++) {
			dfs(x + 1, s + k[x] * pow(i, p[x]));
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		M = sc.nextInt();
		for (int i = 0; i < n; i++) {
			k[i] = sc.nextInt();
			p[i] = sc.nextInt();
		}
		dfs(0,0);
		System.out.println(ans);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_41921315/article/details/87988984
今日推荐