这是一道算法题,我有解法但是有性能问题。
Question Description
There are n variables and m requirements. Requirements are represented as (x <= y), which means the x-th variable must be smaller or equal to the y-th variable. Assign nonnegative numbers smaller than 10 to each variable. Please calculate how many different assignments that match all requirements. Two assignments are different if and only if at least one variable is assigned different number in these two assignment. Module the answer by 1007.
Input Format:
First line of the input contains two integers n and m. Then following m lines each containing 2 space-seperated integers x and y, which means a requirement (x <= y).
Output Format:
Output the answer in one line.
Constraints:
0 < n < 14
0 < m < 200
0 <= x, y < n
Sample Input:
6 7
1 3
0 1
2 4
0 4
2 5
3 4
0 2
Sample Output:
1000
下面是我的解决方案。当 n=13 和 m=199 时,需要很长时间才能得到结果,但可接受的时间是 5 秒。
那么有人能想出更好的方法来进一步优化它吗?谢谢。
我目前的解决方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication81
{
class Program
{
const int N = 10;
static List<Condition> condition = new List<Condition>();
static void Main(string[] args)
{
string[] line1 = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int n = int.Parse(line1[0]);
int m = int.Parse(line1[1]);
for (int i = 0; i < m; i++)
{
string[] line = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
condition.Add(new Condition()
{
X = int.Parse(line[0]),
Y = int.Parse(line[1])
});
}
//
List<int[]> rlist = new List<int[]>();
for (int j = 0; j < N; j++)
{
int[] assignments = new int[n];
for (int i = 0; i < n; i++)
assignments[i] = -1;
assignments[0] = j;
rlist.Add(assignments);
}
for (int j = 1; j < n; j++)
{
List<int[]> rlist2 = new List<int[]>(rlist.Count*5);
for (int k = 0; k < rlist.Count; k++)
{
for (int l = 0; l < N; l++)
{
rlist[k][j] = l;
if (CanPassCondition(rlist[k]))
rlist2.Add((int[])rlist[k].Clone());
}
}
rlist = rlist2;
}
Console.Write(rlist.Count % 1007);
}
private static bool CanPassCondition(int[] p)
{
foreach (var c in condition)
{
if (p[c.X] == -1 || p[c.Y] == -1)
continue;
if (p[c.X] > p[c.Y])
return false;
}
return true;
}
}
class Condition
{
public int X;
public int Y;
public override string ToString()
{
return string.Format("x:{0}, y:{1}", X, Y);
}
}
}
最佳答案
这是一个 Java 解决方案,即使在 n=13、m=199 的情况下,它对我来说也运行得非常快:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Assignments
{
private static Map <String, Long> solutions = new HashMap <String, Long> ();
private static boolean [][] constraints;
private static long solve (int n, int [] low, int [] high)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < n; i++)
{
sb.append (low [i]);
sb.append (high [i]);
}
String signature = sb.toString ();
Long result = solutions.get (signature);
if (result == null)
{
result = Long.valueOf (doSolve (n, low, high));
solutions.put (signature, result);
}
return result.longValue ();
}
private static long doSolve (int n, int [] low, int [] high)
{
if (n == 0) return 1;
else
{
long result = 0;
for (int i = low [n - 1]; i <= high [n - 1]; i++)
{
int [] l = new int [n - 1];
int [] h = new int [n - 1];
for (int j = 0; j < n - 1; j++)
{
l [j] = constraints [n - 1][j] ? Math.max (low [j], i) : low [j];
h [j] = constraints [j][n - 1] ? Math.min (high [j], i) : high [j];
}
result += solve (n - 1, l, h);
}
return result;
}
}
public static void main(String[] args) throws Exception
{
BufferedReader reader =
new BufferedReader (
new InputStreamReader(System.in));
String nm = reader.readLine ();
String [] pair = nm.split(" ");
int n = Integer.parseInt(pair [0]);
int m = Integer.parseInt(pair [1]);
constraints = new boolean [n][];
for (int i = 0; i < n; i++)
constraints [i] = new boolean [n];
int [] low = new int [n];
int [] high = new int [n];
for (int i = 0; i < n; i++)
high [i] = 9;
for (int i = 0; i < m; i++)
{
String ab = reader.readLine();
pair = ab.split (" ");
int a = Integer.parseInt(pair [0]);
int b = Integer.parseInt(pair [1]);
constraints [a][b] = true;
}
System.out.println(solve (n, low, high));
}
}
实际上,一旦你有 13 个变量,你可能只有 156 (13 * 12) 个有意义的约束,但是。
示例输入:
13 1
3 8
输出:
5500000000000
另一个示例输入:
13 12
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
输出:
497420
关于c# - 优化此 C# 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14950853/
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
我如何做Ruby方法"Flatten"RubyMethod在C#中。此方法将锯齿状数组展平为一维数组。例如:s=[1,2,3]#=>[1,2,3]t=[4,5,6,[7,8]]#=>[4,5,6,[7,8]]a=[s,t,9,10]#=>[[1,2,3],[4,5,6,[7,8]],9,10]a.flatten#=>[1,2,3,4,5,6,7,8,9,10 最佳答案 递归解决方案:IEnumerableFlatten(IEnumerablearray){foreach(variteminarray){if(itemisIEnume
我最近从C#转向了Ruby,我发现自己无法制作可折叠的标记代码区域。我只是想到做这种事情应该没问题:classExamplebegin#agroupofmethodsdefmethod1..enddefmethod2..endenddefmethod3..endend...但是这样做真的可以吗?method1和method2最终与method3是同一种东西吗?还是有一些我还没有见过的用于执行此操作的Ruby惯用语? 最佳答案 正如其他人所说,这不会改变方法定义。但是,如果要标记方法组,为什么不使用Ruby语义来标记它们呢?您可以使用
什么是Linq聚合方法的ruby等价物。它的工作原理是这样的varfactorial=new[]{1,2,3,4,5}.Aggregate((acc,i)=>acc*i);每次将数组序列中的值传递给lambda时,变量acc都会累积。 最佳答案 这在数学以及几乎所有编程语言中通常称为折叠。它是更普遍的变形概念的一个实例。Ruby从Smalltalk中继承了这个特性的名称,它被称为inject:into:(像aCollectioninject:aStartValueinto:aBlock一样使用。)所以,在Ruby中,它称为inj
1.问题描述使用Python的turtle(海龟绘图)模块提供的函数绘制直线。2.问题分析一幅复杂的图形通常都可以由点、直线、三角形、矩形、平行四边形、圆、椭圆和圆弧等基本图形组成。其中的三角形、矩形、平行四边形又可以由直线组成,而直线又是由两个点确定的。我们使用Python的turtle模块所提供的函数来绘制直线。在使用之前我们先介绍一下turtle模块的相关知识点。turtle模块提供面向对象和面向过程两种形式的海龟绘图基本组件。面向对象的接口类如下:1)TurtleScreen类:定义图形窗口作为绘图海龟的运动场。它的构造器需要一个tkinter.Canvas或ScrolledCanva
我一直在尝试用Ruby实现Luhn算法。我一直在执行以下步骤:该公式根据其包含的校验位验证数字,该校验位通常附加到部分帐号以生成完整帐号。此帐号必须通过以下测试:从最右边的校验位开始向左移动,每第二个数字的值加倍。将乘积的数字(例如,10=1+0=1、14=1+4=5)与原始数字的未加倍数字相加。如果总模10等于0(如果总和以零结尾),则根据Luhn公式该数字有效;否则无效。http://en.wikipedia.org/wiki/Luhn_algorithm这是我想出的:defvalidCreditCard(cardNumber)sum=0nums=cardNumber.to_s.s
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭8年前。Improvethisquestion几年前我去学校学习编程,毕业后我找到了一份系统管理方面的工作,这就是我职业生涯的方向。我想重新开始某种开发,并且一直在“玩”C#和ASP.NET,但我已经听到很多关于其他"new"语言的讨论(新的意思是它们是新的)我)喜欢Ruby和F#。我想我想知道我是否在浪费时间学习主要的MS语言,而不是成为一名通才。很长一段时间没有离开开发社区(如果我曾经离开过的话)让我在潮流中挣扎,我不想落在时代的