题目链接如下:
开始的代码如下:
#include <cstdio>
#include <vector>
#include <set>
// #define debug
struct stu{
int a;
int b;
};
int n, pos, cnt, kase = 0;
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
while(scanf("%d", &n) == 1 && n){
std::vector<stu> vec(n);
std::set<std::vector<int>> st;
cnt = 0;
std::vector<int> state(n);
for(int i = 0; i < n; ++i){
scanf("%d %d %d", &vec[i].a, &vec[i].b, &state[i]);
if(state[i] > vec[i].a){
++cnt;
}
}
st.insert(state);
pos = 1;
while(cnt){
int tmp = 0;
for(int i = 0; i < n; ++i){
if(2 * cnt <= n && state[i] == vec[i].a){
state[i] = 1;
} else{
state[i] = state[i] % (vec[i].a + vec[i].b) + 1;
if(state[i] > vec[i].a){
tmp++;
}
}
}
if(st.find(state) != st.end()){
pos = -1;
break;
}
st.insert(state);
cnt = tmp;
pos++;
}
printf("Case %d: %d\n", ++kase, pos);
}
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
写完后又看了下其他人的代码,感觉还可以简化一点。也即,只需要把最先的状态init记录下来,重复回到那个状态就判-1,不用引入set那么麻烦。修改后代码如下:
#include <cstdio>
#include <vector>
// #define debug
struct stu{
int a;
int b;
};
int n, pos, cnt, kase = 0;
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
while(scanf("%d", &n) == 1 && n){
std::vector<stu> vec(n);
std::vector<int> init;
cnt = 0;
std::vector<int> state(n);
for(int i = 0; i < n; ++i){
scanf("%d %d %d", &vec[i].a, &vec[i].b, &state[i]);
init.push_back(state[i]);
if(state[i] > vec[i].a){
++cnt;
}
}
pos = 1;
while(cnt){
int tmp = 0;
for(int i = 0; i < n; ++i){
if(2 * cnt <= n && state[i] == vec[i].a){
state[i] = 1;
} else{
state[i] = state[i] % (vec[i].a + vec[i].b) + 1;
if(state[i] > vec[i].a){
tmp++;
}
}
}
if(init == state){
pos = -1;
break;
}
cnt = tmp;
pos++;
}
printf("Case %d: %d\n", ++kase, pos);
}
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}