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

这题直接简单模拟即可。给你n个容器,m个操作,最大容量C。模拟每一个对器件的开关操作。如果原来是关闭的,则打开,同时最大功耗加上这个器件的功耗。如果原来是打开的,就关了它,同时目前的功耗值减去这个器件所消耗的。这个最大功耗时时更新。如果大于C,输出Fuse was blown.否则输出所到达的最大功耗。这个模拟算法很简单,但是我却WA了很久(..........)。直到

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 POJ1484 Blowing Fuses(简单模拟) 算法 第1张
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<vector>
 6 #include<stack>
 7 #include<map>
 8 #include<set>
 9 #include<list>
10 #include<queue>
11 #include<string>
12 #include<algorithm>
13 #include<iomanip>
14 using namespace std;
15 #define MAX 50
16 
17 struct node
18 {
19     int sta;
20     int power;
21 };
22 
23 node arr[MAX] ;
24 
25 int n,m ,c;
26 
27 int main()
28 {
29     int p = 1;
30     while(cin>>n>>m>>c &&  n!= 0 && m!= 0 && c != 0)
31     {
32         int t = 0;//功耗警告
33         int sum = 0;
34         int max = 0;
35         int x;
36         for(int i = 0;i <n;i++)
37         {
38             cin>>arr[i].power;
39             arr[i].sta = 0;//初始为关闭状态
40         }
41         for(int i = 0; i < m;i++)
42         {
43             cin>>x;
44             if(arr[x-1].sta == 0)//当前为关闭状态
45             {
46                 arr[x-1].sta = 1;//打开
47                 sum += arr[x-1].power;
48                 if(sum > max){max = sum;}
49                 if(sum > c)
50                 {
51                     t = 1;
52                     //break;   //加了这个会一直WA,WA 
53                 }
54             }
55             else//当前为打开状态
56             {
57                 arr[x-1].sta = 0;
58                 sum -= arr[x-1].power;
59             }
60         }
61         if(t == 1)
62         {
63             cout<<"Sequence "<<p++<<endl<<"Fuse was blown."<<endl;
64         }
65         else
66         {
67             cout<<"Sequence "<<p++<<endl<<"Fuse was not blown."<<endl<<"Maximal power consumption was "<<max<<" amperes."<<endl;
68         }
69         cout<<endl;//注意格式要求,没有这个换行会 PE
70     }
71     return 0;
72 }
View Code

中间判断功耗大于C时,我将标记置为1,直接break掉,导致WA了半天,其实删掉就可以了(本来就不应该加上去)。因为题目意思把m个操作全部读入才能进行最终判断。中途break掉,虽然逻辑没有什么错误,但是后面的数据实际没有读入,程序不允许这样。

最后,题目的输出格式也要注意下,每个Sequence间有一行间隔

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄