poj 2947 Widget Factory

题目链接:http://poj.org/problem?id=2947


题目大意:

n种项目,每种项目由一个工人在[3,9]天里完成(项目完成时间对于每个人是一样的),给出每个工人开始和结束施工的时间以及完成的项目,求出每个项目需要的时间.


题目思路:

根据题目范围和题意,比较容易想到高斯消元,但是求的是同余方程组(表示搜了题解,学了一下),对每次操作x都写成类似(x%7+7)%7就好了~.


代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

#define ull unsigned __int64
#define ll __int64
//#define ll long long
#define ls rt<<1
#define rs ls|1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle l+r>>1
#define INF 0x3F3F3F3F
#define esp (1e-10)
#define MOD 1000000007
#define type int
typedef pair<int,int> pii;
typedef multiset<int> mset;
typedef multiset<int>::iterator mst_it;
//const double pi=acos(-1.0);
const int M=300 +5;
#define clr(x,c) memset(x,c,sizeof(x))
type min(type x,type y){return x<y? x:y;}
type max(type x,type y){return x>y? x:y;}
void swap(type& x,type& y){type t=x;x=y;y=t;}
int T,cas=0;

int n,m;
int a[M][M],x[M],free_x[M];
map<string,int>mp;
char s1[4],s2[4];

int gcd(int a,int b){
    if(a>b) swap(a,b);
    while(b){int t=b;b=a%b,a=t;}
    return a;
}
 
int lcm(int a,int b){
    return a/gcd(a,b)*b;
}
 
int gauss(int equ,int var){
	int i,j,k,col;
	clr(free_x,0);
	for(k=col=0;k<equ && col<var;k++,col++){
		int max_r=k;
		for(i=k+1;i<equ;i++)
			if(abs(a[i][col])>abs(a[max_r][col])) max_r=i;
		if(max_r!=k)
			for(j=col;j<var+1;j++) swap(a[k][j],a[max_r][j]);
		if(!a[k][col]){k--;free_x[col]=1;continue;}
		for(i=k+1;i<equ;i++) if(a[i][col]){
			int LCM=lcm(abs(a[i][col]),abs(a[k][col]));
			int ti=LCM/abs(a[i][col]);
			int tk=LCM/abs(a[k][col]);
			if(a[i][col]*a[k][col]<0) tk=-tk;
			for(j=col;j<var+1;j++)
				a[i][j]=((ti*a[i][j]-tk*a[k][j])%7+7)%7;
		}
	}
	for(i=k;i<equ;i++)
		if(a[i][var]) return -1;
	if(k<var)
		return var-k;
	for(i=k-1;i>=0;i--){
		int tmp=a[i][var];
		for(j=i+1;j<var;j++) if(a[i][j]){
			tmp-=a[i][j]*x[j];
			tmp=((tmp%7)+7)%7;
		}
		while(tmp%a[i][i]) tmp+=7;
		x[i]=(tmp/a[i][i])%7;
		if(x[i]<3) x[i]+=7;
	}
	return 0;
}

void preSof(){
	mp["MON"]=0,mp["TUE"]=1;
	mp["WED"]=2,mp["THU"]=3;
	mp["FRI"]=4,mp["SAT"]=5;
	mp["SUN"]=6;
	return;
}

void run(){
    int i,j,k;
	clr(a,0);
	for(i=0;i<m;i++){
		scanf("%d%s%s",&k,s1,s2);
		a[i][n]=((mp[s2]-mp[s1]+1)%7+7)%7;
		while(k--) scanf("%d",&j),a[i][j-1]++,a[i][j-1]%=7;
	}
	int ans=gauss(m,n);
	if(ans<0) puts("Inconsistent data.");
	else if(ans) puts("Multiple solutions.");
	else for(i=0;i<n;i++) printf("%d%c",x[i],i==n-1? '\n':' ');
}

int main(){
    //freopen("1.in","r",stdin);
    //freopen("1.out","w",stdout);
	preSof();
    //run();
    while(~scanf("%d%d",&n,&m) && (n||m)) run();
    //for(scanf("%d",&T),cas=1;cas<=T;cas++) run();
    //system("pause");
    return 0;
}

你可能感兴趣的:(poj 2947 Widget Factory)