HDU 4451 Dressing
Dressing
http://acm.hdu.edu.cn/showproblem.php?pid=4451
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1112 Accepted Submission(s): 471
Problem Description
Wangpeng has N clothes, M pants and K shoes so theoretically he can have N×M×K different combinations of dressing. One day he wears his pants Nike, shoes Adiwang to go to school happily. When he opens the door, his mom asks him to come back and switch the dressing. Mom thinks that pants-shoes pair is disharmonious because Adiwang is much better than Nike. After being asked to switch again and again Wangpeng figure out all the pairs mom thinks disharmonious. They can be only clothes-pants pairs or pants-shoes pairs. Please calculate the number of different combinations of dressing under mom’s restriction.
Input
There are multiple test cases. For each case, the first line contains 3 integers N,M,K(1≤N,M,K≤1000) indicating the number of clothes, pants and shoes. Second line contains only one integer P(0≤P≤2000000) indicating the number of pairs which mom thinks disharmonious. Next P lines each line will be one of the two forms“clothes x pants y” or “pants y shoes z”. The first form indicates pair of x-th clothes and y-th pants is disharmonious(1≤x≤N,1 ≤y≤M), and second form indicates pair of y-th pants and z-th shoes is disharmonious(1≤y≤M,1≤z≤K). Input ends with “0 0 0”. It is guaranteed that all the pairs are different.
Output
For each case, output the answer in one line.
Sample Input
2 2 2
0
2 2 2
1
clothes 1 pants 1
2 2 2
2
clothes 1 pants 1
pants 1 shoes 1
0 0 0
Sample Output
8
6
5
Source
就是有N件衣服,M件裤子,K件鞋子。
有一些衣服和裤子是搭配不和谐的,有一些裤子和鞋子是搭配不和谐的。
问有多少种搭配衣服+裤子+鞋子,使得不存在不和谐的。
很简单,不要想得太多。
最直接的方法是枚举每一件组合,找出符合的,复杂度O(N*M*K),这个肯定是超时的。。。
可以降低一维。
枚举每一件衣服和裤子的组合,如果衣服和裤子可以搭配,则看该条裤子可以和多少件鞋子搭配。累加就可以了。
这个的复杂度是O(N*M).这个对于这题已经可以AC了,虽然效率没有很高。
还可以再降低一维。
枚举每条裤子,可以和这条裤子搭配的衣服数乘以可以和这条衣服搭配的鞋子数。累加起来就是答案。
复杂度O(M).
代码,按照第二种思路写的。
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; char str1[20],str2[20]; int d1,d2; int m,n,k,p; int a[1005][1005],b[1005][1005],c[1005]; int main(){ int i,j; while(scanf("%d%d%d",&m,&n,&k) && (m || n || k)){ scanf("%d",&p); memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(c,0,sizeof(c)); for(i=0;i<p;i++){ scanf("%s%d%s%d",str1,&d1,str2,&d2); if(strcmp(str1,"clothes")==0) a[d1][d2]=1; else{ if(b[d1][d2]==0){ b[d1][d2]=1; c[d1]++; } } } int ans=0; for(i=1;i<=m;i++) for(j=1;j<=n;j++) if(!a[i][j]) ans+=k-c[j]; printf("%d\n",ans); } return 0; }