UVa 11742 – Social Constraints

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
	int n,m,i,ways,incr,temp,first[21],second[21],dif[21],perm[9];

	while (true){
		cin>>n>>m;
		if (n==0 && m==0) return 0;
		for (i = 0 ; i < m ;i++)
			cin>>first[i]>>second[i]>>dif[i];

		for(i= 0 ; i  < n ; i++)
			perm[i] = i;

		ways = 0;
		incr = 0;
		do{
			incr = 1;
			for(i =0 ; i < m ; i ++){
				temp = abs(perm[first[i]] - perm[second[i]]);
				if ((dif[i]>0 && temp>dif[i]) || (dif[i]<0 && temp<-dif[i]) ){
					incr = 0;
					break;
				}
			}
			ways+=incr;
		}while (next_permutation(perm,perm+n));

		cout<<ways<<endl;
	}
	return 0;
}